问:
Type Error and got an unexpected keyword argument: When passing dict to Python Zeep's Client.Service call
I have the following XML which I am sending to the target web application using SOAPUI and it works.

```<code><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <RequestMessage xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message">
         <Header>
            <Verb>create</Verb>
            <Noun>OutageSet</Noun>
            <ReplayDetection>
               <Nonce>72465</Nonce>
               <Created>2022-12-27T00:40:00-07:00</Created>
            </ReplayDetection>
            <Revision>004</Revision>
            <Source>TAEPTC</Source>
            <!--Optional:-->
            <UserID>API_OutplanOSITCC</UserID>
         </Header>
         <Payload>
            <OutageSet xmlns="http://www.ercot.com/schema/2007-06/nodal/ews">
               <Outage>
                  <OutageInfo>
                     <outageType>PL</outageType>
                     <Requestor>
                        <name>API_OutplanOSITCC</name>
                        <userFullName>APIOutplanOSITCC</userFullName>
                     </Requestor>
                     <Disclaimer>tempdisclaimer</Disclaimer>
                     <disclaimerAck>true</disclaimerAck>
                  </OutageInfo>
                  <TransmissionOutage>
                     <operatingCompany>TAEPTC</operatingCompany>
                     <equipmentName>1589</equipmentName>
                     <equipmentIdentifier>_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}</equipmentIdentifier>
                     <transmissionType>DSC</transmissionType>
                     <fromStation>AIRLINE</fromStation>
                     <outageState>O</outageState>
                     <emergencyRestorationTime>1</emergencyRestorationTime>
                     <natureOfWork>OE</natureOfWork>
                  </TransmissionOutage>
                  <Schedule>
                     <plannedStart>2023-01-16T10:00:00</plannedStart>
                     <plannedEnd>2023-01-17T10:00:00</plannedEnd>
                     <earliestStart>2023-01-16T10:00:00</earliestStart>
                     <latestEnd>2023-01-17T12:00:00</latestEnd>
                  </Schedule>
               </Outage>
            </OutageSet>
         </Payload>
      </RequestMessage>
   </soapenv:Body>
</soapenv:Envelope>
</code>```

I am trying to generate the XML using python's zeep module and for that I have the modifeid xml and converting that to dict using xmltodict module.
Below is the XMLtoDIct code sinppet -

```<code>import xmltodict
import pprint
import json

my_xml = """
          <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <RequestMessage xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message">
         <Header>
            <Verb>create</Verb>
            <Noun>OutageSet</Noun>
            <ReplayDetection>
               <Nonce>72465</Nonce>
               <Created>2022-12-27T00:40:00-07:00</Created>
            </ReplayDetection>
            <Revision>004</Revision>
            <Source>TAEPTC</Source>
            <!--Optional:-->
            <UserID>API_OutplanOSITCC</UserID>
         </Header>
         <Payload>
            <OutageSet xmlns="http://www.ercot.com/schema/2007-06/nodal/ews">
               <Outage>
                  <OutageInfo>
                     <outageType>PL</outageType>
                     <Requestor>
                        <name>API_OutplanOSITCC</name>
                        <userFullName>APIOutplanOSITCC</userFullName>
                     </Requestor>
                     <Disclaimer>tempdisclaimer</Disclaimer>
                     <disclaimerAck>true</disclaimerAck>
                  </OutageInfo>
                  <TransmissionOutage>
                     <operatingCompany>TAEPTC</operatingCompany>
                     <equipmentName>1589</equipmentName>
                     <equipmentIdentifier>_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}</equipmentIdentifier>
                     <transmissionType>DSC</transmissionType>
                     <fromStation>AIRLINE</fromStation>
                     <outageState>O</outageState>
                     <emergencyRestorationTime>1</emergencyRestorationTime>
                     <natureOfWork>OE</natureOfWork>
                  </TransmissionOutage>
                  <Schedule>
                     <plannedStart>2023-01-16T10:00:00</plannedStart>
                     <plannedEnd>2023-01-17T10:00:00</plannedEnd>
                     <earliestStart>2023-01-16T10:00:00</earliestStart>
                     <latestEnd>2023-01-17T12:00:00</latestEnd>
                  </Schedule>
               </Outage>
            </OutageSet>
         </Payload>
      </RequestMessage>
   </soapenv:Body>
</soapenv:Envelope>

"""
my_dict = xmltodict.parse(my_xml, process_namespaces= True)
#pp = pprint.PrettyPrinter(indent=2)
print(my_dict)
</code>```

Below is the dict after conversion -

```<code>{'http://schemas.xmlsoap.org/soap/envelope/:Envelope': {'http://schemas.xmlsoap.org/soap/envelope/:Header': None, 'http://schemas.xmlsoap.org/soap/envelope/:Body': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}}}
</code>```

however, when I am passing this dict to the request data like below -

```<code>request_data = {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}

print("Call URL")
print(client.service.MarketTransactions(**request_data))
</code>```

I am getting the below error -

```<code>Creating client.
zeep.transports: Loading remote data from: http://www.w3.org/2001/xml.xsd
Making request.
Call URL
Traceback (most recent call last):
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\ERCOT_Test.py", line 110, in <module>
    print(client.service.MarketTransactions(**request_data))
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\proxy.py", line 46, in __call__
    return self._proxy._binding.send(
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\bindings\soap.py", line 123, in send
    envelope, http_headers = self._create(
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\bindings\soap.py", line 73, in _create
    serialized = operation_obj.create(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\definitions.py", line 222, in create
    return self.input.serialize(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\messages\soap.py", line 73, in serialize
    body_value = self.body(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\elements\element.py", line 58, in __call__
    instance = self.type(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\types\complex.py", line 63, in __call__
    return self._value_class(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\valueobjects.py", line 106, in __init__
    items = _process_signature(self._xsd_type, args, kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\valueobjects.py", line 241, in _process_signature
    raise TypeError(
TypeError: {http://www.ercot.com/schema/2007-06/nodal/ews/message}RequestMessage() got an unexpected keyword argument 'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage'. Signature: `Header: {http://www.ercot.com/schema/2007-06/nodal/ews/message}HeaderType, Request: {http://www.ercot.com/schema/2007-06/nodal/ews/message}RequestType, Payload: {http://www.ercot.com/schema/2007-06/nodal/ews/message}PayloadType`

Process finished with exit code 1
</code>```

is this because of the namespaces in both RequestMessage and Outageset nodes?
Here is my complete code -

```<code>from zeep.wsse.signature import BinarySignature
from zeep.wsse import utils
from datetime import datetime, timedelta
import contextlib
import os
import requests
from requests_pkcs12 import Pkcs12Adapter
from zeep.transports import Transport
from zeep import Client, Settings
from pathlib import Path
from tempfile import NamedTemporaryFile
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
import random
import logging.config

# USE THE MOST VERBOSE LOGGING LEVEL
logging.config.dictConfig({
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(name)s: %(message)s'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'zeep.transports': {
            'level': 'DEBUG',
            'propagate': True,
            'handlers': ['console'],
        },
    }
})

class BinarySignatureTimestamp(BinarySignature):
    def apply(self, envelope, headers):
        security = utils.get_security_header(envelope)

        created = datetime.utcnow()
        expired = created + timedelta(seconds=1 * 60)

        timestamp = utils.WSU('Timestamp')
        timestamp.append(utils.WSU('Created', created.replace(microsecond=0).isoformat() + 'Z'))
        timestamp.append(utils.WSU('Expires', expired.replace(microsecond=0).isoformat() + 'Z'))

        security.append(timestamp)

        super().apply(envelope, headers)
        return envelope, headers

    def verify(self, envelope):
        return envelope

@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
    ''' Decrypts the .pfx file to be used with requests. '''
    pfx = Path(pfx_path).read_bytes()
    private_key, main_cert, add_certs = load_key_and_certificates(pfx, pfx_password.encode('utf-8'), None)

    with NamedTemporaryFile(suffix='.pem', delete=False) as t_pem:
        with open(t_pem.name, 'wb') as pem_file:
            pem_file.write(private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))
            pem_file.write(main_cert.public_bytes(Encoding.PEM))
            for ca in add_certs:
                pem_file.write(ca.public_bytes(Encoding.PEM))
        yield t_pem.name

def generate_nonce(length=15):
    """Generate pseudorandom number."""
    return ''.join([str(random.randint(0, 9)) for i in range(length)])

# CERTIFICATES PATHS

api_p12_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.p12')
api_certificate = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\OSITCC.crt')
api_pfx_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.pfx')

# SETUP
wsdl_file = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\Nodal.wsdl')

api_base_url = "https://testmisapi.ercot.com"
session = requests.Session()
session.mount(api_base_url,
              Pkcs12Adapter(pkcs12_filename=api_p12_key, pkcs12_password='HIDDEN'))
session.verify = None

transport = Transport(session=session)
settings = Settings(forbid_entities=False)

# CREATE CLIENT
print("Creating client.")
with pfx_to_pem(pfx_path=api_pfx_key, pfx_password='AEP') as pem_fle:
    client = Client(wsdl=wsdl_file, settings=settings, transport=transport,
                    wsse=BinarySignatureTimestamp(pem_fle, api_certificate, "AEP"))

print("Making request.")
request_data = {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}

print("Call URL")
print(client.service.MarketTransactions(**request_data))
</code>```

The same code is working when I am calling another webservice just by sending the header(does not have a namespace) in the request data like below -

```<code>from zeep.wsse.signature import BinarySignature
from zeep.wsse import utils
from datetime import datetime, timedelta
import contextlib
import os
import requests
from requests_pkcs12 import Pkcs12Adapter
from zeep.transports import Transport
from zeep import Client, Settings
from pathlib import Path
from tempfile import NamedTemporaryFile
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
import random
import logging.config

# USE THE MOST VERBOSE LOGGING LEVEL
logging.config.dictConfig({
 'version': 1,
 'formatters': {
 'verbose': {
 'format': '%(name)s: %(message)s'
 }
 },
 'handlers': {
 'console': {
 'level': 'DEBUG',
 'class': 'logging.StreamHandler',
 'formatter': 'verbose',
 },
 },
 'loggers': {
 'zeep.transports': {
 'level': 'DEBUG',
 'propagate': True,
 'handlers': ['console'],
 },
 }
})

class BinarySignatureTimestamp(BinarySignature):
    def apply(self, envelope, headers):
        security = utils.get_security_header(envelope)

        created = datetime.utcnow()
        expired = created + timedelta(seconds=1 * 60)

        timestamp = utils.WSU('Timestamp')
        timestamp.append(utils.WSU('Created', created.replace(microsecond=0).isoformat()+'Z'))
        timestamp.append(utils.WSU('Expires', expired.replace(microsecond=0).isoformat()+'Z'))

        security.append(timestamp)

        super().apply(envelope, headers)
        return envelope, headers

    def verify(self, envelope):
        return envelope

@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
 ''' Decrypts the .pfx file to be used with requests. '''
 pfx = Path(pfx_path).read_bytes()
 private_key, main_cert, add_certs = load_key_and_certificates(pfx, pfx_password.encode('utf-8'), None)

 with NamedTemporaryFile(suffix='.pem', delete=False) as t_pem:
   with open(t_pem.name, 'wb') as pem_file:
     pem_file.write(private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))
     pem_file.write(main_cert.public_bytes(Encoding.PEM))
     for ca in add_certs:
       pem_file.write(ca.public_bytes(Encoding.PEM))
   yield t_pem.name

def generate_nonce(length=15):
 """Generate pseudorandom number."""
 return ''.join([str(random.randint(0, 9)) for i in range(length)])

# CERTIFICATES PATHS

api_p12_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.p12')
api_certificate = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\OSITCC.crt')
api_pfx_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.pfx')

# SETUP
wsdl_file = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\Nodal.wsdl')

api_base_url = "https://testmisapi.ercot.com"
session = requests.Session()
session.mount(api_base_url,
 Pkcs12Adapter(pkcs12_filename=api_p12_key, pkcs12_password='AEP'))
session.verify = None

transport = Transport(session=session)
settings = Settings(forbid_entities=False)

# CREATE CLIENT
print("Creating client.")
with pfx_to_pem(pfx_path=api_pfx_key, pfx_password='hidden') as pem_fle:
   client = Client(wsdl=wsdl_file, settings=settings, transport=transport,
   wsse=BinarySignatureTimestamp(pem_fle, api_certificate, "AEP"))

print("Making request.")
request_data = {
 "Header": {
 "Verb": "get",
 "Noun": "SystemStatus",
 "ReplayDetection": {
 "Nonce": generate_nonce(),
 "Created": "2022-11-10T15:34:00-06:00"},
 "Revision": "1",
 "Source": "API Outplan OSI TCC",
 "UserID": "API_OutplanOSITCC",
 }
 }

print("Call URL")
print(client.service.MarketInfo(**request_data))
</code>```

Could anyone please advise how to fix this and what needs to be changed?

Thanks
Sugata

Body:
I have the following XML which I am sending to the target web application using SOAPUI and it works.

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <RequestMessage xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message">

            <Verb>create</Verb>
            <Noun>OutageSet</Noun>
            <ReplayDetection>
               <Nonce>72465</Nonce>
               <Created>2022-12-27T00:40:00-07:00</Created>
            </ReplayDetection>
            <Revision>004</Revision>
            <Source>TAEPTC</Source>

            <UserID>API_OutplanOSITCC</UserID>

         <Payload>
            <OutageSet xmlns="http://www.ercot.com/schema/2007-06/nodal/ews">
               <Outage>
                  <OutageInfo>
                     <outageType>PL</outageType>
                     <Requestor>
                        <name>API_OutplanOSITCC</name>
                        <userFullName>APIOutplanOSITCC</userFullName>
                     </Requestor>
                     <Disclaimer>tempdisclaimer</Disclaimer>
                     <disclaimerAck>true</disclaimerAck>
                  </OutageInfo>
                  <TransmissionOutage>
                     <operatingCompany>TAEPTC</operatingCompany>
                     <equipmentName>1589</equipmentName>
                     <equipmentIdentifier>_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}</equipmentIdentifier>
                     <transmissionType>DSC</transmissionType>
                     <fromStation>AIRLINE</fromStation>
                     <outageState>O</outageState>
                     <emergencyRestorationTime>1</emergencyRestorationTime>
                     <natureOfWork>OE</natureOfWork>
                  </TransmissionOutage>
                  <Schedule>
                     <plannedStart>2023-01-16T10:00:00</plannedStart>
                     <plannedEnd>2023-01-17T10:00:00</plannedEnd>
                     <earliestStart>2023-01-16T10:00:00</earliestStart>
                     <latestEnd>2023-01-17T12:00:00</latestEnd>
                  </Schedule>
               </Outage>
            </OutageSet>
         </Payload>
      </RequestMessage>
   </soapenv:Body>
</soapenv:Envelope>

I am trying to generate the XML using python's zeep module and for that I have the modifeid xml and converting that to dict using xmltodict module.
Below is the XMLtoDIct code sinppet -

import xmltodict
import pprint
import json

my_xml = """
          <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:wsu="http://www.docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
   <soapenv:Header/>
   <soapenv:Body>
      <RequestMessage xmlns="http://www.ercot.com/schema/2007-06/nodal/ews/message">

            <Verb>create</Verb>
            <Noun>OutageSet</Noun>
            <ReplayDetection>
               <Nonce>72465</Nonce>
               <Created>2022-12-27T00:40:00-07:00</Created>
            </ReplayDetection>
            <Revision>004</Revision>
            <Source>TAEPTC</Source>

            <UserID>API_OutplanOSITCC</UserID>

         <Payload>
            <OutageSet xmlns="http://www.ercot.com/schema/2007-06/nodal/ews">
               <Outage>
                  <OutageInfo>
                     <outageType>PL</outageType>
                     <Requestor>
                        <name>API_OutplanOSITCC</name>
                        <userFullName>APIOutplanOSITCC</userFullName>
                     </Requestor>
                     <Disclaimer>tempdisclaimer</Disclaimer>
                     <disclaimerAck>true</disclaimerAck>
                  </OutageInfo>
                  <TransmissionOutage>
                     <operatingCompany>TAEPTC</operatingCompany>
                     <equipmentName>1589</equipmentName>
                     <equipmentIdentifier>_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}</equipmentIdentifier>
                     <transmissionType>DSC</transmissionType>
                     <fromStation>AIRLINE</fromStation>
                     <outageState>O</outageState>
                     <emergencyRestorationTime>1</emergencyRestorationTime>
                     <natureOfWork>OE</natureOfWork>
                  </TransmissionOutage>
                  <Schedule>
                     <plannedStart>2023-01-16T10:00:00</plannedStart>
                     <plannedEnd>2023-01-17T10:00:00</plannedEnd>
                     <earliestStart>2023-01-16T10:00:00</earliestStart>
                     <latestEnd>2023-01-17T12:00:00</latestEnd>
                  </Schedule>
               </Outage>
            </OutageSet>
         </Payload>
      </RequestMessage>
   </soapenv:Body>
</soapenv:Envelope>

"""
my_dict = xmltodict.parse(my_xml, process_namespaces= True)
#pp = pprint.PrettyPrinter(indent=2)
print(my_dict)

Below is the dict after conversion -

{'http://schemas.xmlsoap.org/soap/envelope/:Envelope': {'http://schemas.xmlsoap.org/soap/envelope/:Header': None, 'http://schemas.xmlsoap.org/soap/envelope/:Body': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}}}

however, when I am passing this dict to the request data like below -

request_data = {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}

print("Call URL")
print(client.service.MarketTransactions(**request_data))

I am getting the below error -

Creating client.
zeep.transports: Loading remote data from: http://www.w3.org/2001/xml.xsd
Making request.
Call URL
Traceback (most recent call last):
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\ERCOT_Test.py", line 110, in <module>
    print(client.service.MarketTransactions(**request_data))
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\proxy.py", line 46, in __call__
    return self._proxy._binding.send(
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\bindings\soap.py", line 123, in send
    envelope, http_headers = self._create(
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\bindings\soap.py", line 73, in _create
    serialized = operation_obj.create(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\definitions.py", line 222, in create
    return self.input.serialize(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\wsdl\messages\soap.py", line 73, in serialize
    body_value = self.body(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\elements\element.py", line 58, in __call__
    instance = self.type(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\types\complex.py", line 63, in __call__
    return self._value_class(*args, **kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\valueobjects.py", line 106, in __init__
    items = _process_signature(self._xsd_type, args, kwargs)
  File "C:\Users\SGUPTA\PycharmProjects\ERCOT\venv\lib\site-packages\zeep\xsd\valueobjects.py", line 241, in _process_signature
    raise TypeError(
TypeError: {http://www.ercot.com/schema/2007-06/nodal/ews/message}RequestMessage() got an unexpected keyword argument 'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage'. Signature: `Header: {http://www.ercot.com/schema/2007-06/nodal/ews/message}HeaderType, Request: {http://www.ercot.com/schema/2007-06/nodal/ews/message}RequestType, Payload: {http://www.ercot.com/schema/2007-06/nodal/ews/message}PayloadType`

Process finished with exit code 1

is this because of the namespaces in both RequestMessage and Outageset nodes?
Here is my complete code -

from zeep.wsse.signature import BinarySignature
from zeep.wsse import utils
from datetime import datetime, timedelta
import contextlib
import os
import requests
from requests_pkcs12 import Pkcs12Adapter
from zeep.transports import Transport
from zeep import Client, Settings
from pathlib import Path
from tempfile import NamedTemporaryFile
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
import random
import logging.config

# USE THE MOST VERBOSE LOGGING LEVEL
logging.config.dictConfig({
    'version': 1,
    'formatters': {
        'verbose': {
            'format': '%(name)s: %(message)s'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'verbose',
        },
    },
    'loggers': {
        'zeep.transports': {
            'level': 'DEBUG',
            'propagate': True,
            'handlers': ['console'],
        },
    }
})

class BinarySignatureTimestamp(BinarySignature):
    def apply(self, envelope, headers):
        security = utils.get_security_header(envelope)

        created = datetime.utcnow()
        expired = created + timedelta(seconds=1 * 60)

        timestamp = utils.WSU('Timestamp')
        timestamp.append(utils.WSU('Created', created.replace(microsecond=0).isoformat() + 'Z'))
        timestamp.append(utils.WSU('Expires', expired.replace(microsecond=0).isoformat() + 'Z'))

        security.append(timestamp)

        super().apply(envelope, headers)
        return envelope, headers

    def verify(self, envelope):
        return envelope

@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
    ''' Decrypts the .pfx file to be used with requests. '''
    pfx = Path(pfx_path).read_bytes()
    private_key, main_cert, add_certs = load_key_and_certificates(pfx, pfx_password.encode('utf-8'), None)

    with NamedTemporaryFile(suffix='.pem', delete=False) as t_pem:
        with open(t_pem.name, 'wb') as pem_file:
            pem_file.write(private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))
            pem_file.write(main_cert.public_bytes(Encoding.PEM))
            for ca in add_certs:
                pem_file.write(ca.public_bytes(Encoding.PEM))
        yield t_pem.name

def generate_nonce(length=15):
    """Generate pseudorandom number."""
    return ''.join([str(random.randint(0, 9)) for i in range(length)])

# CERTIFICATES PATHS

api_p12_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.p12')
api_certificate = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\OSITCC.crt')
api_pfx_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.pfx')

# SETUP
wsdl_file = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\Nodal.wsdl')

api_base_url = "https://testmisapi.ercot.com"
session = requests.Session()
session.mount(api_base_url,
              Pkcs12Adapter(pkcs12_filename=api_p12_key, pkcs12_password='HIDDEN'))
session.verify = None

transport = Transport(session=session)
settings = Settings(forbid_entities=False)

# CREATE CLIENT
print("Creating client.")
with pfx_to_pem(pfx_path=api_pfx_key, pfx_password='AEP') as pem_fle:
    client = Client(wsdl=wsdl_file, settings=settings, transport=transport,
                    wsse=BinarySignatureTimestamp(pem_fle, api_certificate, "AEP"))

print("Making request.")
request_data = {'http://www.ercot.com/schema/2007-06/nodal/ews/message:RequestMessage': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Header': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Verb': 'create', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Noun': 'OutageSet', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:ReplayDetection': {'http://www.ercot.com/schema/2007-06/nodal/ews/message:Nonce': '72465', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Created': '2022-12-27T00:40:00-07:00'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Revision': '004', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Source': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews/message:UserID': 'API_OutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews/message:Payload': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageSet': {'http://www.ercot.com/schema/2007-06/nodal/ews:Outage': {'http://www.ercot.com/schema/2007-06/nodal/ews:OutageInfo': {'http://www.ercot.com/schema/2007-06/nodal/ews:outageType': 'PL', 'http://www.ercot.com/schema/2007-06/nodal/ews:Requestor': {'http://www.ercot.com/schema/2007-06/nodal/ews:name': 'API_OutplanOSITCC', 'http://www.ercot.com/schema/2007-06/nodal/ews:userFullName': 'APIOutplanOSITCC'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Disclaimer': 'tempdisclaimer', 'http://www.ercot.com/schema/2007-06/nodal/ews:disclaimerAck': 'true'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:TransmissionOutage': {'http://www.ercot.com/schema/2007-06/nodal/ews:operatingCompany': 'TAEPTC', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentName': '1589', 'http://www.ercot.com/schema/2007-06/nodal/ews:equipmentIdentifier': '_{072D6FCA-D121-49E7-AC9D-CDF5D4DB3D70}', 'http://www.ercot.com/schema/2007-06/nodal/ews:transmissionType': 'DSC', 'http://www.ercot.com/schema/2007-06/nodal/ews:fromStation': 'AIRLINE', 'http://www.ercot.com/schema/2007-06/nodal/ews:outageState': 'O', 'http://www.ercot.com/schema/2007-06/nodal/ews:emergencyRestorationTime': '1', 'http://www.ercot.com/schema/2007-06/nodal/ews:natureOfWork': 'OE'}, 'http://www.ercot.com/schema/2007-06/nodal/ews:Schedule': {'http://www.ercot.com/schema/2007-06/nodal/ews:plannedStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:plannedEnd': '2023-01-17T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:earliestStart': '2023-01-16T10:00:00', 'http://www.ercot.com/schema/2007-06/nodal/ews:latestEnd': '2023-01-17T12:00:00'}}}}}}

print("Call URL")
print(client.service.MarketTransactions(**request_data))

The same code is working when I am calling another webservice just by sending the header(does not have a namespace) in the request data like below -

from zeep.wsse.signature import BinarySignature
from zeep.wsse import utils
from datetime import datetime, timedelta
import contextlib
import os
import requests
from requests_pkcs12 import Pkcs12Adapter
from zeep.transports import Transport
from zeep import Client, Settings
from pathlib import Path
from tempfile import NamedTemporaryFile
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
from cryptography.hazmat.primitives.serialization.pkcs12 import load_key_and_certificates
import random
import logging.config

# USE THE MOST VERBOSE LOGGING LEVEL
logging.config.dictConfig({
 'version': 1,
 'formatters': {
 'verbose': {
 'format': '%(name)s: %(message)s'
 }
 },
 'handlers': {
 'console': {
 'level': 'DEBUG',
 'class': 'logging.StreamHandler',
 'formatter': 'verbose',
 },
 },
 'loggers': {
 'zeep.transports': {
 'level': 'DEBUG',
 'propagate': True,
 'handlers': ['console'],
 },
 }
})

class BinarySignatureTimestamp(BinarySignature):
    def apply(self, envelope, headers):
        security = utils.get_security_header(envelope)

        created = datetime.utcnow()
        expired = created + timedelta(seconds=1 * 60)

        timestamp = utils.WSU('Timestamp')
        timestamp.append(utils.WSU('Created', created.replace(microsecond=0).isoformat()+'Z'))
        timestamp.append(utils.WSU('Expires', expired.replace(microsecond=0).isoformat()+'Z'))

        security.append(timestamp)

        super().apply(envelope, headers)
        return envelope, headers

    def verify(self, envelope):
        return envelope

@contextlib.contextmanager
def pfx_to_pem(pfx_path, pfx_password):
 ''' Decrypts the .pfx file to be used with requests. '''
 pfx = Path(pfx_path).read_bytes()
 private_key, main_cert, add_certs = load_key_and_certificates(pfx, pfx_password.encode('utf-8'), None)

 with NamedTemporaryFile(suffix='.pem', delete=False) as t_pem:
   with open(t_pem.name, 'wb') as pem_file:
     pem_file.write(private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()))
     pem_file.write(main_cert.public_bytes(Encoding.PEM))
     for ca in add_certs:
       pem_file.write(ca.public_bytes(Encoding.PEM))
   yield t_pem.name

def generate_nonce(length=15):
 """Generate pseudorandom number."""
 return ''.join([str(random.randint(0, 9)) for i in range(length)])

# CERTIFICATES PATHS

api_p12_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.p12')
api_certificate = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\OSITCC.crt')
api_pfx_key = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\API Outplan OSI TCC MOTE.pfx')

# SETUP
wsdl_file = os.path.join('C:\\Users\\SGUPTA\\ALL\\Projects\\AEPE2\\Nodal.wsdl')

api_base_url = "https://testmisapi.ercot.com"
session = requests.Session()
session.mount(api_base_url,
 Pkcs12Adapter(pkcs12_filename=api_p12_key, pkcs12_password='AEP'))
session.verify = None

transport = Transport(session=session)
settings = Settings(forbid_entities=False)

# CREATE CLIENT
print("Creating client.")
with pfx_to_pem(pfx_path=api_pfx_key, pfx_password='hidden') as pem_fle:
   client = Client(wsdl=wsdl_file, settings=settings, transport=transport,
   wsse=BinarySignatureTimestamp(pem_fle, api_certificate, "AEP"))

print("Making request.")
request_data = {
 "Header": {
 "Verb": "get",
 "Noun": "SystemStatus",
 "ReplayDetection": {
 "Nonce": generate_nonce(),
 "Created": "2022-11-10T15:34:00-06:00"},
 "Revision": "1",
 "Source": "API Outplan OSI TCC",
 "UserID": "API_OutplanOSITCC",
 }
 }

print("Call URL")
print(client.service.MarketInfo(**request_data))

Could anyone please advise how to fix this and what needs to be changed?

Thanks
Sugata


来源: stackexchange

问:
Issue when running the job in EMR 6.6.0 using Spark 3.2.0
My job(Spark-Scala) is running fine in emr-5.36.0 using spark 2.4.8 and scala 2.11.

But I am getting below error while running the same job in emr-6.6.0 using spark 3.2.0 and scala 2.12.15

Exception in thread "main" java.lang.IncompatibleClassChangeError: Class org.json.JSONArray does not implement the requested interface java.lang.Iterable

As per my understanding below part of code is causing issue

```<code>*import scala.collection.JavaConverters._
val configJSON: JSONArray = fetchConfigs(configServerUri, configFiles)
configJSON.asScala.foreach(propertySource => {
  propertySource.asInstanceOf[JSONObject].getJSONObject("source").toMap.asScala.foreach(kv => {
    sparkAppConf.set(configReMap.getOrElse(kv._1, kv._1), kv._2.toString)
  })*
</code>```

I am using below dependency in pom for json:

```<code><dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220924</version>
</dependency>
</code>```

And JSONArray is implementing the Iterable:

```<code>**public class JSONArray implements Iterable<Object>**
</code>```

Note:The same code is running fine in local with spark 3.2.0 and scala 2.12.15.

ContentLicense: CC BY-SA 4.0

Body:
My job(Spark-Scala) is running fine in emr-5.36.0 using spark 2.4.8 and scala 2.11.

But I am getting below error while running the same job in emr-6.6.0 using spark 3.2.0 and scala 2.12.15

Exception in thread "main" java.lang.IncompatibleClassChangeError: Class org.json.JSONArray does not implement the requested interface java.lang.Iterable

As per my understanding below part of code is causing issue

*import scala.collection.JavaConverters._
val configJSON: JSONArray = fetchConfigs(configServerUri, configFiles)
configJSON.asScala.foreach(propertySource => {
  propertySource.asInstanceOf[JSONObject].getJSONObject("source").toMap.asScala.foreach(kv => {
    sparkAppConf.set(configReMap.getOrElse(kv._1, kv._1), kv._2.toString)
  })*

I am using below dependency in pom for json:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20220924</version>
</dependency>

And JSONArray is implementing the Iterable:

**public class JSONArray implements Iterable<Object>**

Note:The same code is running fine in local with spark 3.2.0 and scala 2.12.15.


问:
Insert or upsert or delete row in Big Query based on condition with efficient way
Here is my input json format

```<code>{
  "ID": "ABC34567",
  "NUM": "45678",
  "ORG_ID": "161",
  "CONTACT_NUMBER": null,
  "FLAG": "N"
}
</code>```

I need to check whether ID is already present or not. If present, need to update the Data else insert a row. If FLAG:"Del", Need to Delete if ID is already present in BigQuery table else leave as is.

I am struggling how to achieve above functionality in python.

To insert a json, I know below code in python using BigQuery API,

```<code>rows_to_insert = [{"ID":"sdf1234","NUM":"4567890","ORG_ID":"567","CONTACT_NUMBER":"456789", "FLAG":"N"}]

errors = client.insert_rows_json(table_id,rows_to_insert)
</code>```

I found below code on internet,

```<code>from google.cloud import bigquery

client = bigquery.Client()

query_job = client.query(
    """
    MERGE my-dataset.json_table T
USING my-dataset.json_table_source S
ON T.ID = S.ID
WHEN MATCHED THEN
  UPDATE SET string_field_1 = s.string_field_1
WHEN NOT MATCHED THEN
  INSERT (int64_field_0, string_field_1) VALUES(int64_field_0, string_field_1)"""
)

results = query_job.result()  # Waits for job to complete.
</code>```

I am totally stuck how can i able to pass json in above query or any other best way to update the existing row

Please guide me how can i achieve this in BigQuery API using python

Body:
Here is my input json format

{
  "ID": "ABC34567",
  "NUM": "45678",
  "ORG_ID": "161",
  "CONTACT_NUMBER": null,
  "FLAG": "N"
}

I need to check whether ID is already present or not. If present, need to update the Data else insert a row. If FLAG:"Del", Need to Delete if ID is already present in BigQuery table else leave as is.

I am struggling how to achieve above functionality in python.

To insert a json, I know below code in python using BigQuery API,

rows_to_insert = [{"ID":"sdf1234","NUM":"4567890","ORG_ID":"567","CONTACT_NUMBER":"456789", "FLAG":"N"}]

errors = client.insert_rows_json(table_id,rows_to_insert)

I found below code on internet,

from google.cloud import bigquery

client = bigquery.Client()

query_job = client.query(
    """
    MERGE my-dataset.json_table T
USING my-dataset.json_table_source S
ON T.ID = S.ID
WHEN MATCHED THEN
  UPDATE SET string_field_1 = s.string_field_1
WHEN NOT MATCHED THEN
  INSERT (int64_field_0, string_field_1) VALUES(int64_field_0, string_field_1)"""
)

results = query_job.result()  # Waits for job to complete.

I am totally stuck how can i able to pass json in above query or any other best way to update the existing row

Please guide me how can i achieve this in BigQuery API using python


问:
How is isinstance implemented in Python?
I know what the isinstance(inst, cls) function does in Python, but I cannot seem to understand how it is implemented under the hood in the standard implementation of Python (CPython).

Here's a Python-based function I've made to try to reproduce the functionality of isinstance. But I have no idea how it actually works.

def _isinstance(obj: object, cls: type) -> bool:
    if hasattr(obj, "__instancecheck__") and hasattr(obj.__instancecheck__, "__call__"):
        return obj.__instancecheck__(cls)

    if type(obj) is type:
        return cls in (*obj.__mro__, obj.__class__)
    else:
        return cls in obj.__class__.__mro__
```

If you could include a similar _isinstance function along with your explanation, I'd be very thankful. Thanks in advance.

Body:
I know what the isinstance(inst, cls) function does in Python, but I cannot seem to understand how it is implemented under the hood in the standard implementation of Python (CPython).

Here's a Python-based function I've made to try to reproduce the functionality of isinstance. But I have no idea how it actually works.

def _isinstance(obj: object, cls: type) -> bool:
    if hasattr(obj, "__instancecheck__") and hasattr(obj.__instancecheck__, "__call__"):
        return obj.__instancecheck__(cls)

    if type(obj) is type:
        return cls in (*obj.__mro__, obj.__class__)
    else:
        return cls in obj.__class__.__mro__

If you could include a similar _isinstance function along with your explanation, I'd be very thankful. Thanks in advance.


问:
How to obtain the precise values of the streets of a city with OSMnx?
I want to make a traffic simulator of a city and for that I need to get the exact location of the streets and then plot them.

To draw the map I'm taking the streets of omsnx, but these have some flaws.Here I show how it looks like using the omsnx.plot_graph() function.

But using the values of G.edges() and building the graph myself there are inconsistencies like extra streets. This is an example of what the graph looks like using exactly the values provided by the edges.

Note that both images show the same traffic circle.

So the question is how to obtain the real street values without noise, i.e. without several streets playing the role of one.

This is the code I use to plot with pygame.

import osmnx as ox
address_name='Ciudad Deportiva, Havana, Cuba'

#Import graph
point = (23.1021, -82.3936)
G = ox.graph_from_point(point, dist=1000, retain_all=True, simplify=True, network_type='drive')
G = ox.project_graph(G)

import pygame
from map import Map

RED = (255, 0, 0)
BLUE = (0, 0, 20)
GRAY = (215,215,215)
WHITE = (255, 255, 255)

inc = 0.8

m = Map(1400, 800, lng=inc*2555299.469922482, lat=inc*356731.10053785384, i_zoom=0.1)

last_x = -1
last_y = -1
i=0
while True:

    for event in pygame.event.get():

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                m.inc_zoom()
            elif event.button == 5:
                m.dec_zoom()

        if event.type == pygame.MOUSEMOTION:
            if event.buttons[0] == 1:
                if last_x == last_y == -1:
                    last_x, last_y = event.pos
                else:
                    m.x += (event.pos[0] - last_x)/2
                    m.y += (event.pos[1] - last_y)/2
                    last_x, last_y = event.pos

        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                last_x = last_y = -1

        m.fill(GRAY)

        # Here I take the coordinates of the streets and paint them
        for _, _, data in G.edges(data=True):
            try:
                m.draw_road(data['geometry'], inc, BLUE)
            except:
                pass

        m.update()
```
<p>Other functions and objects I use for plotting. This is the code of <code>map.py</code></p>
<pre class="lang-py prettyprint-override"><code>from typing import List, Tuple
from window import Window
from pygame import gfxdraw
from shapely.geometry import LineString

def build_rect(
        start: Tuple[float,float],
        end: Tuple[float,float],
        width: float = 3
    ) -> List[Tuple[float,float]]:

    x0, y0 = start
    x1, y1 = end

    if x0**2 + y0**2 > x1**2 + y1**2:
        x0, y0 = end
        x1, y1 = start

    # vector from start to end
    vX, vY = x1 - x0, y1 - y0
    # normal vector
    nX, nY = -vY, vX

    # normalize
    n = (nX**2 + nY**2)**0.5
    nX, nY = width/n * nX, width/n * nY

    # third vector
    x2, y2 = x1 + nX, y1 + nY
    # fourth vector
    x3, y3 = x0 + nX, y0 + nY

    return [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]

class Map(Window):

    def __init__(self, width, height, **kwargs):
        super().__init__(width, height, **kwargs)

    def draw_road(self, st: LineString, inc: float, color: Tuple[float,float,float]):
        last = None
        for c in st.__geo_interface__['coordinates']:
            c = (inc*c[0], inc*c[1])
            if last == None:
                last = (c[0] - self.lat,c[1] - self.lng)
                continue

            lat = c[0] - self.lat
            lng = c[1] - self.lng

            pts = build_rect(last, (lat, lng))

            gfxdraw.filled_polygon(self.screen, [
                (self.x + lat * self.zoom, self.y + lng * self.zoom)
                for lat, lng in pts
            ], color)
</code>```

And this is the code of window.py.

import pygame
from pygame import gfxdraw
from pygame.locals import *

class Window:

    def __init__(self, width, height, **kwargs):
        self.width = width
        self.height = height

        self.zoom = 1
        self.x = self.y = 0
        self.i_zoom = 0.001

        self.__dict__.update(kwargs)

        pygame.init()
        self.screen = pygame.display.set_mode((width, height))

    def inc_zoom(self):
        self.zoom += self.i_zoom

    def dec_zoom(self):
        self.zoom -= self.i_zoom
        self.zoom = max(0, self.zoom)

    def draw_polygon(self, points, color):
        gfxdraw.filled_polygon(self.screen, [
            (self.x + pt[0] *  self.zoom, self.y + pt[1] * self.zoom)
            for pt in points], color)

    def fill(self, color):
        self.screen.fill(color)

    def update(self):
        pygame.display.update()
```

Body:
I want to make a traffic simulator of a city and for that I need to get the exact location of the streets and then plot them.

To draw the map I'm taking the streets of omsnx, but these have some flaws.Here I show how it looks like using the omsnx.plot_graph() function.

But using the values of G.edges() and building the graph myself there are inconsistencies like extra streets. This is an example of what the graph looks like using exactly the values provided by the edges.

Note that both images show the same traffic circle.

So the question is how to obtain the real street values without noise, i.e. without several streets playing the role of one.

This is the code I use to plot with pygame.

import osmnx as ox
address_name='Ciudad Deportiva, Havana, Cuba'

#Import graph
point = (23.1021, -82.3936)
G = ox.graph_from_point(point, dist=1000, retain_all=True, simplify=True, network_type='drive')
G = ox.project_graph(G)

import pygame
from map import Map

RED = (255, 0, 0)
BLUE = (0, 0, 20)
GRAY = (215,215,215)
WHITE = (255, 255, 255)

inc = 0.8

m = Map(1400, 800, lng=inc*2555299.469922482, lat=inc*356731.10053785384, i_zoom=0.1)

last_x = -1
last_y = -1
i=0
while True:

    for event in pygame.event.get():

        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 4:
                m.inc_zoom()
            elif event.button == 5:
                m.dec_zoom()

        if event.type == pygame.MOUSEMOTION:
            if event.buttons[0] == 1:
                if last_x == last_y == -1:
                    last_x, last_y = event.pos
                else:
                    m.x += (event.pos[0] - last_x)/2
                    m.y += (event.pos[1] - last_y)/2
                    last_x, last_y = event.pos

        if event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                last_x = last_y = -1

        m.fill(GRAY)

        # Here I take the coordinates of the streets and paint them
        for _, _, data in G.edges(data=True):
            try:
                m.draw_road(data['geometry'], inc, BLUE)
            except:
                pass

        m.update()

Other functions and objects I use for plotting. This is the code of map.py

from typing import List, Tuple
from window import Window
from pygame import gfxdraw
from shapely.geometry import LineString

def build_rect(
        start: Tuple[float,float],
        end: Tuple[float,float],
        width: float = 3
    ) -> List[Tuple[float,float]]:

    x0, y0 = start
    x1, y1 = end

    if x0**2 + y0**2 > x1**2 + y1**2:
        x0, y0 = end
        x1, y1 = start

    # vector from start to end
    vX, vY = x1 - x0, y1 - y0
    # normal vector
    nX, nY = -vY, vX

    # normalize
    n = (nX**2 + nY**2)**0.5
    nX, nY = width/n * nX, width/n * nY

    # third vector
    x2, y2 = x1 + nX, y1 + nY
    # fourth vector
    x3, y3 = x0 + nX, y0 + nY

    return [(x0, y0), (x1, y1), (x2, y2), (x3, y3)]

class Map(Window):

    def __init__(self, width, height, **kwargs):
        super().__init__(width, height, **kwargs)

    def draw_road(self, st: LineString, inc: float, color: Tuple[float,float,float]):
        last = None
        for c in st.__geo_interface__['coordinates']:
            c = (inc*c[0], inc*c[1])
            if last == None:
                last = (c[0] - self.lat,c[1] - self.lng)
                continue

            lat = c[0] - self.lat
            lng = c[1] - self.lng

            pts = build_rect(last, (lat, lng))

            gfxdraw.filled_polygon(self.screen, [
                (self.x + lat * self.zoom, self.y + lng * self.zoom)
                for lat, lng in pts
            ], color)

And this is the code of window.py.

import pygame
from pygame import gfxdraw
from pygame.locals import *

class Window:

    def __init__(self, width, height, **kwargs):
        self.width = width
        self.height = height

        self.zoom = 1
        self.x = self.y = 0
        self.i_zoom = 0.001

        self.__dict__.update(kwargs)

        pygame.init()
        self.screen = pygame.display.set_mode((width, height))

    def inc_zoom(self):
        self.zoom += self.i_zoom

    def dec_zoom(self):
        self.zoom -= self.i_zoom
        self.zoom = max(0, self.zoom)

    def draw_polygon(self, points, color):
        gfxdraw.filled_polygon(self.screen, [
            (self.x + pt[0] *  self.zoom, self.y + pt[1] * self.zoom)
            for pt in points], color)

    def fill(self, color):
        self.screen.fill(color)

    def update(self):
        pygame.display.update()


问:
Download file using fetch with Javascript always corrupt
i'm try to download file with javascript when load the window automatically, but the file always get corrupted

```<code><!DOCTYPE html>
<html>
    <head>
        <title>test</title>

        <script>
            function downloadFile(url, fileName) {
            fetch(url, { method: 'get', mode: 'no-cors', referrerPolicy: 'no-referrer' })
                .then(res => res.blob())
                .then(res => {
                    const aElement = document.createElement('a');
                    aElement.setAttribute('download', fileName);
                    const href = URL.createObjectURL(res);
                    aElement.href = href;
                    aElement.setAttribute('target', '_blank');
                    aElement.click();
                    URL.revokeObjectURL(href);
                });
            };
        </script>
    </head>
    <body>
    <script>
        window.onload = function() {
        downloadFile('./tes.pdf', 'tes.pdf');
    };
    </script>
    </body>
</html>
</code>```

this is my code

why always get file corrupted ?

Body:
i'm try to download file with javascript when load the window automatically, but the file always get corrupted

<!DOCTYPE html>

        <title>test</title>

this is my code

why always get file corrupted ?


问:
Shopify fetch id of an image (media id) inside of .js.liquid
I am trying to fetch ID of my product images inside of .js.liquid files. It is easy to do so from .liquid file directly but can't figure out how to do it from a .js file. In a .liquid file I simply put {{ media.id }} and it works, but trying different things in .js won't do the job. I tried to search for the issue but can't find anything...

I tried different types of code. Basically I have a string which generates a html for my product images on my homepage.

```<code>      thumbnailContainer.append('<img src="' + src +'" alt="qv-img" class="lazyload">');
</code>```

src + works fine, but when trying "media.id" or "id", it doesn't work properly. Can someone navigate me into the right direction?

Body:
I am trying to fetch ID of my product images inside of .js.liquid files. It is easy to do so from .liquid file directly but can't figure out how to do it from a .js file. In a .liquid file I simply put {{ media.id }} and it works, but trying different things in .js won't do the job. I tried to search for the issue but can't find anything...

I tried different types of code. Basically I have a string which generates a html for my product images on my homepage.

      thumbnailContainer.append('');

src + works fine, but when trying "media.id" or "id", it doesn't work properly. Can someone navigate me into the right direction?


问:
How to add LayerGroups to a marker in React Leaflet
I'm getting confused about LayerGroups in React Leaflet.

I am iterating through an object with markers in React Leaflet (using Gatsby), and when I add the marker I want to assign the LayerGroup based on an attribute in the object I am iterating through.

Currently the main bit of the code looks like this:

```<code>const IndexPage = ({ data }) => (
    <main>
        <MapContainer style={{ height: '100vh', width: '100vw'}} center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
        <TileLayer
            attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
          {
            data.allMarkdownRemark.edges.map((edge, i) => (
              <Marker position={edge.node.frontmatter.location}>
                <Popup>
                {edge.node.frontmatter.Name}
                </Popup>
            </Marker>
            ))
          }
        </MapContainer>
    </main>
  )
</code>```

How do I add and create LayerGroups?

In React Leaflet, you seem to do so by adding <LayerGroup> tags and then nest the markers within the correct one, but I'm not sure how that would work with my scenario. If I weren't using React I would do aMarker.addTo(aLayerGroup) - but I'm not sure how I'm supposed to be doing that in the React context.

Body:
I'm getting confused about LayerGroups in React Leaflet.

I am iterating through an object with markers in React Leaflet (using Gatsby), and when I add the marker I want to assign the LayerGroup based on an attribute in the object I am iterating through.

Currently the main bit of the code looks like this:

const IndexPage = ({ data }) => (

        <MapContainer style={{ height: '100vh', width: '100vw'}} center={[51.505, -0.09]} zoom={13} scrollWheelZoom={false}>
        <TileLayer
            attribution='© OpenStreetMap contributors'
            url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
          {
            data.allMarkdownRemark.edges.map((edge, i) => (
              <Marker position={edge.node.frontmatter.location}>
                <Popup>
                {edge.node.frontmatter.Name}
                </Popup>
            </Marker>
            ))
          }
        </MapContainer>

  )

How do I add and create LayerGroups?

In React Leaflet, you seem to do so by adding <LayerGroup> tags and then nest the markers within the correct one, but I'm not sure how that would work with my scenario. If I weren't using React I would do aMarker.addTo(aLayerGroup) - but I'm not sure how I'm supposed to be doing that in the React context.


问:
Flutter: Appending / streaming data to secure storage item
I am developing an app in Flutter that loads files from a server and saves them to secure local storage for later offline use.

I am running into issues with larger documents (e.g. a 150megs PDF), resulting in OutOfMemoryError s on Android.

Is there a way to "append" bytes to a secure storage item or have something like a streaming approach?

Thanks!

Update: I am using the "flutter_secure_file_storage" package.

```<code>import 'package:flutter_secure_file_storage/flutter_secure_file_storage.dart';

final localStorageManager = LocalStorageManager._(
    FlutterSecureFileStorage(const FlutterSecureStorage()));

class LocalStorageManager {
  final LocalStorageItemMap<DocumentContent> documentContents;

  LocalStorageManager._(FlutterSecureFileStorage secureStorage)
      : storageVersion =
            LocalStorageItem(secureStorage, key: "storage_version"),
        settings = LocalStorageSettingsItems._(secureStorage),
        login = LocalStorageLoginItems._(secureStorage),
        documentContents =
            LocalStorageItemMap(secureStorage, "document_contents_");
</code>```

Body:
I am developing an app in Flutter that loads files from a server and saves them to secure local storage for later offline use.

I am running into issues with larger documents (e.g. a 150megs PDF), resulting in OutOfMemoryError s on Android.

Is there a way to "append" bytes to a secure storage item or have something like a streaming approach?

Thanks!

Update: I am using the "flutter_secure_file_storage" package.

import 'package:flutter_secure_file_storage/flutter_secure_file_storage.dart';

final localStorageManager = LocalStorageManager._(
    FlutterSecureFileStorage(const FlutterSecureStorage()));

class LocalStorageManager {
  final LocalStorageItemMap<DocumentContent> documentContents;

  LocalStorageManager._(FlutterSecureFileStorage secureStorage)
      : storageVersion =
            LocalStorageItem(secureStorage, key: "storage_version"),
        settings = LocalStorageSettingsItems._(secureStorage),
        login = LocalStorageLoginItems._(secureStorage),
        documentContents =
            LocalStorageItemMap(secureStorage, "document_contents_");


问:
How can I hide Label Prices from lower time frames on current timeframe?
Can anyone guide me in the correct direction to hide the open label prices from lower timeframes than the select timeframe that I am on? (ex I am on the quarter timeframe and I want to hide the open label prices on everything lower than that? I will include part of the code here.

```<code>f_get_o(back, res) =>
    O = request.security(symbol=syminfo.tickerid, timeframe=res, expression=open[back], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
    O

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// CALCULATIONS
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OL_1h_res = '60'
OL_D_res = 'D'
OL_W_res = 'W'
OL_M_res = 'M'
OL_3M_res = '3M'
OL_6M_res = '6M'
OL_12M_res = '12M'

OL_1h_passed = ta.barssince(ta.change(time(OL_1h_res)) != 0)
OL_D_passed = ta.barssince(ta.change(time(OL_D_res)) != 0)
OL_W_passed = ta.barssince(ta.change(time(OL_W_res)) != 0)
OL_M_passed = ta.barssince(ta.change(time(OL_M_res)) != 0)
OL_3M_passed = ta.barssince(ta.change(time(OL_3M_res)) != 0)
OL_6M_passed = ta.barssince(ta.change(time(OL_6M_res)) != 0)
OL_12M_passed = ta.barssince(ta.change(time(OL_12M_res)) != 0)

OL_change = ta.change(time)

OL_1h_x1 = time + math.round(OL_change * -OL_1h_passed)
OL_D_x1 = time + math.round(OL_change * -OL_D_passed)
OL_W_x1 = time + math.round(OL_change * -OL_W_passed)
OL_M_x1 = time + math.round(OL_change * -OL_M_passed)
OL_3M_x1 = time + math.round(OL_change * -OL_3M_passed)
OL_6M_x1 = time + math.round(OL_change * -OL_6M_passed)
OL_12M_x1 = time + math.round(OL_change * -OL_12M_passed)

OL_xn = time + math.round(OL_change * OL_offset)

OL_1h_o = f_get_o(0, OL_1h_res)
OL_D_o = f_get_o(0, OL_D_res)
OL_W_o = f_get_o(0, OL_W_res)
OL_M_o = f_get_o(0, OL_M_res)
OL_3M_o = f_get_o(0, OL_3M_res)
OL_6M_o = f_get_o(0, OL_6M_res)
OL_12M_o = f_get_o(0, OL_12M_res)

var line OL_1h_Line = na
var line OL_D_Line = na
var line OL_W_Line = na
var line OL_M_Line = na
var line OL_3M_Line = na
var line OL_6M_Line = na
var line OL_12M_Line = na

var label OL_1h_Label = na
var label OL_D_Label = na
var label OL_W_Label = na
var label OL_M_Label = na
var label OL_3M_Label = na
var label OL_6M_Label = na
var label OL_12M_Label = na

text_1h = OL_1h_res + ', ' + str.tostring(open[OL_1h_passed])
text_D = OL_D_res + ', ' + str.tostring(open[OL_D_passed])
text_W = OL_W_res + ', ' + str.tostring(open[OL_W_passed])
text_M = OL_M_res + ', ' + str.tostring(open[OL_M_passed])
text_3M = OL_3M_res + ', ' + str.tostring(open[OL_3M_passed])
text_6M = OL_6M_res + ', ' + str.tostring(open[OL_6M_passed])
text_12M = OL_12M_res + ', ' + str.tostring(open[OL_12M_passed])

OL_line_style := OL_line_style == 'Solid' ? line.style_solid : OL_line_style == 'Dashed' ? line.style_dashed : OL_line_style == 'Dotted' ? line.style_dotted : line.style_solid
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// DRAWING
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if OL_1h_show and OL_1h_o[1] != OL_1h_o
    OL_1h_Line := line.new(x1=OL_1h_x1, y1=OL_1h_o, x2=OL_xn, y2=OL_1h_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L1h, style=OL_line_style, width=OL_line_width)
    line.delete(OL_1h_Line[1])
    if OL_label_show
        OL_1h_Label := label.new(x=OL_xn, y=OL_1h_o, xloc=xloc.bar_time, text=text_1h, color=OL_color_L1h, textcolor=OL_color_T1h, style=label.style_label_left)
        label.delete(OL_1h_Label[1])

if OL_D_show and OL_D_o[1] != OL_D_o
    OL_D_Line := line.new(x1=OL_D_x1, y1=OL_D_o, x2=OL_xn, y2=OL_D_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LD, style=OL_line_style, width=OL_line_width)
    line.delete(OL_D_Line[1])
    if OL_label_show
        OL_D_Label := label.new(x=OL_xn, y=OL_D_o, xloc=xloc.bar_time, text=text_D, color=OL_color_LD, textcolor=OL_color_TD, style=label.style_label_left)
        label.delete(OL_D_Label[1])

if OL_W_show and OL_W_o[1] != OL_W_o
    OL_W_Line := line.new(x1=OL_W_x1, y1=OL_W_o, x2=OL_xn, y2=OL_W_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LW, style=OL_line_style, width=OL_line_width)
    line.delete(OL_W_Line[1])
    if OL_label_show
        OL_W_Label := label.new(x=OL_xn, y=OL_W_o, xloc=xloc.bar_time, text=text_W, color=OL_color_LW, textcolor=OL_color_TW, style=label.style_label_left)
        label.delete(OL_W_Label[1])

if OL_M_show and OL_M_o[1] != OL_M_o
    OL_M_Line := line.new(x1=OL_M_x1, y1=OL_M_o, x2=OL_xn, y2=OL_M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LM, style=OL_line_style, width=OL_line_width)
    line.delete(OL_M_Line[1])
    if OL_label_show
        OL_M_Label := label.new(x=OL_xn, y=OL_M_o, xloc=xloc.bar_time, text=text_M, color=OL_color_LM, textcolor=OL_color_TM, style=label.style_label_left)
        label.delete(OL_M_Label[1])

if OL_3M_show and OL_3M_o[1] != OL_3M_o
    OL_3M_Line := line.new(x1=OL_3M_x1, y1=OL_3M_o, x2=OL_xn, y2=OL_3M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L3M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_3M_Line[1])
    if OL_label_show
        OL_3M_Label := label.new(x=OL_xn, y=OL_3M_o, xloc=xloc.bar_time, text=text_3M, color=OL_color_L3M, textcolor=OL_color_T3M, style=label.style_label_left)
        label.delete(OL_3M_Label[1])

if OL_6M_show and OL_6M_o[1] != OL_6M_o
    OL_6M_Line := line.new(x1=OL_6M_x1, y1=OL_6M_o, x2=OL_xn, y2=OL_6M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L6M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_6M_Line[1])
    if OL_label_show
        OL_6M_Label := label.new(x=OL_xn, y=OL_6M_o, xloc=xloc.bar_time, text=text_6M, color=OL_color_L6M, textcolor=OL_color_T6M, style=label.style_label_left)
        label.delete(OL_6M_Label[1])

if OL_12M_show and OL_12M_o[1] != OL_12M_o
    OL_12M_Line := line.new(x1=OL_12M_x1, y1=OL_12M_o, x2=OL_xn, y2=OL_12M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L12M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_12M_Line[1])
    if OL_label_show
        OL_12M_Label := label.new(x=OL_xn, y=OL_12M_o, xloc=xloc.bar_time, text=text_12M, color=OL_color_L12M, textcolor=OL_color_T12M, style=label.style_label_left)
        label.delete(OL_12M_Label[1])

if line.get_x2(OL_1h_Line) != bar_index
    line.set_x2(OL_1h_Line, OL_xn)

if line.get_x2(OL_D_Line) != bar_index
    line.set_x2(OL_D_Line, OL_xn)

if line.get_x2(OL_W_Line) != bar_index
    line.set_x2(OL_W_Line, OL_xn)

if line.get_x2(OL_M_Line) != bar_index
    line.set_x2(OL_M_Line, OL_xn)

if line.get_x2(OL_3M_Line) != bar_index
    line.set_x2(OL_3M_Line, OL_xn)

if line.get_x2(OL_6M_Line) != bar_index
    line.set_x2(OL_6M_Line, OL_xn)

if line.get_x2(OL_12M_Line) != bar_index
    line.set_x2(OL_12M_Line, OL_xn)

if OL_1h_show and OL_label_show and label.get_x(OL_1h_Label) != bar_index
    label.set_x(OL_1h_Label, OL_xn)

if OL_D_show and OL_label_show and label.get_x(OL_D_Label) != bar_index
    label.set_x(OL_D_Label, OL_xn)

if OL_W_show and OL_label_show and label.get_x(OL_W_Label) != bar_index
    label.set_x(OL_W_Label, OL_xn)

if OL_M_show and OL_label_show and label.get_x(OL_M_Label) != bar_index
    label.set_x(OL_M_Label, OL_xn)

if OL_3M_show and OL_label_show and label.get_x(OL_3M_Label) != bar_index
    label.set_x(OL_3M_Label, OL_xn)

if OL_6M_show and OL_label_show and label.get_x(OL_6M_Label) != bar_index
    label.set_x(OL_6M_Label, OL_xn)

if OL_12M_show and OL_label_show and label.get_x(OL_12M_Label) != bar_index
    label.set_x(OL_12M_Label, OL_xn)
</code>```

I have tried to mess with the barmerge and lookahead but I think I hit a couple walls here as it didn't change what I wanted.

Edit: Typo

Body:
Can anyone guide me in the correct direction to hide the open label prices from lower timeframes than the select timeframe that I am on? (ex I am on the quarter timeframe and I want to hide the open label prices on everything lower than that? I will include part of the code here.

f_get_o(back, res) =>
    O = request.security(symbol=syminfo.tickerid, timeframe=res, expression=open[back], gaps=barmerge.gaps_off, lookahead=barmerge.lookahead_on)
    O

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// CALCULATIONS
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OL_1h_res = '60'
OL_D_res = 'D'
OL_W_res = 'W'
OL_M_res = 'M'
OL_3M_res = '3M'
OL_6M_res = '6M'
OL_12M_res = '12M'

OL_1h_passed = ta.barssince(ta.change(time(OL_1h_res)) != 0)
OL_D_passed = ta.barssince(ta.change(time(OL_D_res)) != 0)
OL_W_passed = ta.barssince(ta.change(time(OL_W_res)) != 0)
OL_M_passed = ta.barssince(ta.change(time(OL_M_res)) != 0)
OL_3M_passed = ta.barssince(ta.change(time(OL_3M_res)) != 0)
OL_6M_passed = ta.barssince(ta.change(time(OL_6M_res)) != 0)
OL_12M_passed = ta.barssince(ta.change(time(OL_12M_res)) != 0)

OL_change = ta.change(time)

OL_1h_x1 = time + math.round(OL_change * -OL_1h_passed)
OL_D_x1 = time + math.round(OL_change * -OL_D_passed)
OL_W_x1 = time + math.round(OL_change * -OL_W_passed)
OL_M_x1 = time + math.round(OL_change * -OL_M_passed)
OL_3M_x1 = time + math.round(OL_change * -OL_3M_passed)
OL_6M_x1 = time + math.round(OL_change * -OL_6M_passed)
OL_12M_x1 = time + math.round(OL_change * -OL_12M_passed)

OL_xn = time + math.round(OL_change * OL_offset)

OL_1h_o = f_get_o(0, OL_1h_res)
OL_D_o = f_get_o(0, OL_D_res)
OL_W_o = f_get_o(0, OL_W_res)
OL_M_o = f_get_o(0, OL_M_res)
OL_3M_o = f_get_o(0, OL_3M_res)
OL_6M_o = f_get_o(0, OL_6M_res)
OL_12M_o = f_get_o(0, OL_12M_res)

var line OL_1h_Line = na
var line OL_D_Line = na
var line OL_W_Line = na
var line OL_M_Line = na
var line OL_3M_Line = na
var line OL_6M_Line = na
var line OL_12M_Line = na

var label OL_1h_Label = na
var label OL_D_Label = na
var label OL_W_Label = na
var label OL_M_Label = na
var label OL_3M_Label = na
var label OL_6M_Label = na
var label OL_12M_Label = na

text_1h = OL_1h_res + ', ' + str.tostring(open[OL_1h_passed])
text_D = OL_D_res + ', ' + str.tostring(open[OL_D_passed])
text_W = OL_W_res + ', ' + str.tostring(open[OL_W_passed])
text_M = OL_M_res + ', ' + str.tostring(open[OL_M_passed])
text_3M = OL_3M_res + ', ' + str.tostring(open[OL_3M_passed])
text_6M = OL_6M_res + ', ' + str.tostring(open[OL_6M_passed])
text_12M = OL_12M_res + ', ' + str.tostring(open[OL_12M_passed])

OL_line_style := OL_line_style == 'Solid' ? line.style_solid : OL_line_style == 'Dashed' ? line.style_dashed : OL_line_style == 'Dotted' ? line.style_dotted : line.style_solid
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///// DRAWING
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if OL_1h_show and OL_1h_o[1] != OL_1h_o
    OL_1h_Line := line.new(x1=OL_1h_x1, y1=OL_1h_o, x2=OL_xn, y2=OL_1h_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L1h, style=OL_line_style, width=OL_line_width)
    line.delete(OL_1h_Line[1])
    if OL_label_show
        OL_1h_Label := label.new(x=OL_xn, y=OL_1h_o, xloc=xloc.bar_time, text=text_1h, color=OL_color_L1h, textcolor=OL_color_T1h, style=label.style_label_left)
        label.delete(OL_1h_Label[1])

if OL_D_show and OL_D_o[1] != OL_D_o
    OL_D_Line := line.new(x1=OL_D_x1, y1=OL_D_o, x2=OL_xn, y2=OL_D_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LD, style=OL_line_style, width=OL_line_width)
    line.delete(OL_D_Line[1])
    if OL_label_show
        OL_D_Label := label.new(x=OL_xn, y=OL_D_o, xloc=xloc.bar_time, text=text_D, color=OL_color_LD, textcolor=OL_color_TD, style=label.style_label_left)
        label.delete(OL_D_Label[1])

if OL_W_show and OL_W_o[1] != OL_W_o
    OL_W_Line := line.new(x1=OL_W_x1, y1=OL_W_o, x2=OL_xn, y2=OL_W_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LW, style=OL_line_style, width=OL_line_width)
    line.delete(OL_W_Line[1])
    if OL_label_show
        OL_W_Label := label.new(x=OL_xn, y=OL_W_o, xloc=xloc.bar_time, text=text_W, color=OL_color_LW, textcolor=OL_color_TW, style=label.style_label_left)
        label.delete(OL_W_Label[1])

if OL_M_show and OL_M_o[1] != OL_M_o
    OL_M_Line := line.new(x1=OL_M_x1, y1=OL_M_o, x2=OL_xn, y2=OL_M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_LM, style=OL_line_style, width=OL_line_width)
    line.delete(OL_M_Line[1])
    if OL_label_show
        OL_M_Label := label.new(x=OL_xn, y=OL_M_o, xloc=xloc.bar_time, text=text_M, color=OL_color_LM, textcolor=OL_color_TM, style=label.style_label_left)
        label.delete(OL_M_Label[1])

if OL_3M_show and OL_3M_o[1] != OL_3M_o
    OL_3M_Line := line.new(x1=OL_3M_x1, y1=OL_3M_o, x2=OL_xn, y2=OL_3M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L3M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_3M_Line[1])
    if OL_label_show
        OL_3M_Label := label.new(x=OL_xn, y=OL_3M_o, xloc=xloc.bar_time, text=text_3M, color=OL_color_L3M, textcolor=OL_color_T3M, style=label.style_label_left)
        label.delete(OL_3M_Label[1])

if OL_6M_show and OL_6M_o[1] != OL_6M_o
    OL_6M_Line := line.new(x1=OL_6M_x1, y1=OL_6M_o, x2=OL_xn, y2=OL_6M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L6M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_6M_Line[1])
    if OL_label_show
        OL_6M_Label := label.new(x=OL_xn, y=OL_6M_o, xloc=xloc.bar_time, text=text_6M, color=OL_color_L6M, textcolor=OL_color_T6M, style=label.style_label_left)
        label.delete(OL_6M_Label[1])

if OL_12M_show and OL_12M_o[1] != OL_12M_o
    OL_12M_Line := line.new(x1=OL_12M_x1, y1=OL_12M_o, x2=OL_xn, y2=OL_12M_o, xloc=xloc.bar_time, extend=extend.none, color=OL_color_L12M, style=OL_line_style, width=OL_line_width)
    line.delete(OL_12M_Line[1])
    if OL_label_show
        OL_12M_Label := label.new(x=OL_xn, y=OL_12M_o, xloc=xloc.bar_time, text=text_12M, color=OL_color_L12M, textcolor=OL_color_T12M, style=label.style_label_left)
        label.delete(OL_12M_Label[1])

if line.get_x2(OL_1h_Line) != bar_index
    line.set_x2(OL_1h_Line, OL_xn)

if line.get_x2(OL_D_Line) != bar_index
    line.set_x2(OL_D_Line, OL_xn)

if line.get_x2(OL_W_Line) != bar_index
    line.set_x2(OL_W_Line, OL_xn)

if line.get_x2(OL_M_Line) != bar_index
    line.set_x2(OL_M_Line, OL_xn)

if line.get_x2(OL_3M_Line) != bar_index
    line.set_x2(OL_3M_Line, OL_xn)

if line.get_x2(OL_6M_Line) != bar_index
    line.set_x2(OL_6M_Line, OL_xn)

if line.get_x2(OL_12M_Line) != bar_index
    line.set_x2(OL_12M_Line, OL_xn)

if OL_1h_show and OL_label_show and label.get_x(OL_1h_Label) != bar_index
    label.set_x(OL_1h_Label, OL_xn)

if OL_D_show and OL_label_show and label.get_x(OL_D_Label) != bar_index
    label.set_x(OL_D_Label, OL_xn)

if OL_W_show and OL_label_show and label.get_x(OL_W_Label) != bar_index
    label.set_x(OL_W_Label, OL_xn)

if OL_M_show and OL_label_show and label.get_x(OL_M_Label) != bar_index
    label.set_x(OL_M_Label, OL_xn)

if OL_3M_show and OL_label_show and label.get_x(OL_3M_Label) != bar_index
    label.set_x(OL_3M_Label, OL_xn)

if OL_6M_show and OL_label_show and label.get_x(OL_6M_Label) != bar_index
    label.set_x(OL_6M_Label, OL_xn)

if OL_12M_show and OL_label_show and label.get_x(OL_12M_Label) != bar_index
    label.set_x(OL_12M_Label, OL_xn)

I have tried to mess with the barmerge and lookahead but I think I hit a couple walls here as it didn't change what I wanted.

Edit: Typo


问:
JSONDecodeError at /log-in/ Expecting value: line 1 column 1 (char 0)
i am making a website where you can link your ROBLOX account to the website with only the username but i have had an error which i dont know how to fix it. If you know how to fix this error please tell me since this has been very frustrating.

**
Traceback:**

```<code>Traceback (most recent call last):
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

During handling of the above exception (Expecting value: line 1 column 1 (char 0)), another exception occurred:
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Gebruiker\Desktop\Ro-Sky Front-end\base\views.py", line 88, in auth
    if robloxpy.User.External.DoesNameExist(request.POST['username']) == "Unavailible":
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\robloxpy\User\External.py", line 217, in DoesNameExist
    return response.json()
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
</code>```

This is the code the error should be coming from:

```<code>def auth(request):
    if not request.user.is_authenticated:
        isAvailible = None
        code = None
        if request.method == "POST":
            isAvailible = False
            if robloxpy.User.External.DoesNameExist(request.POST['username']) == "Unavailible":
                user = str(request.POST['username']).lower()
                data = requests.get(f'https://api.roblox.com/users/get-by-username?username={user}').json()
                print(user)
                user = data['Username']
                id = data['Id']
                desc = robloxpy.User.External.GetDescription(id)

                isAvailible = True
                user = str(request.POST['username']).lower()
                print(user)
                print(User.objects.filter(username=user))
                if User.objects.filter(username=user).exists():
                    code = User.objects.get(username=request.POST.get('username')).auth_code

                    if desc != None and User.objects.get(username=user).auth_code in desc:
                        userchange = User.objects.get(username=user)
                        userchange.auth_code = randomVerify()
                        userchange.save()
                        login(request, User.objects.get(username=user))
                        return redirect('home')
                else:
                    id = requests.get(f'https://api.roblox.com/users/get-by-username?username={user}').json()['Id']
                    created_user = User(username=user, rbx_id=id)
                    created_user.save()
                    code = created_user.auth_code

        content = {"available": isAvailible, "code": code}

        print(isAvailible)

        return render(request, 'auth.html', content)
    else:
        return redirect('dashboard')

def logout_acc(request):
    logout(request)
    return redirect('auth')

def welcome(request):
    if request.user.is_authenticated:
        id = requests.post(f'https://users.roblox.com/v1/usernames/users', data={
        "usernames": [
            request.user.username
        ],
        "excludeBannedUsers": True
        }).json()["data"][0]['id']
        avatar_uri = f"https://www.roblox.com/headshot-thumbnail/image?userId={id}&width=60&height=60&format=png"
        content = {'avatar_uri': avatar_uri}
        return render(request, 'welcome.html', content)
    else:
        return redirect('auth')
</code>```

Body:
i am making a website where you can link your ROBLOX account to the website with only the username but i have had an error which i dont know how to fix it. If you know how to fix this error please tell me since this has been very frustrating.

**
Traceback:**

Traceback (most recent call last):
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None

During handling of the above exception (Expecting value: line 1 column 1 (char 0)), another exception occurred:
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Gebruiker\Desktop\Ro-Sky Front-end\base\views.py", line 88, in auth
    if robloxpy.User.External.DoesNameExist(request.POST['username']) == "Unavailible":
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\robloxpy\User\External.py", line 217, in DoesNameExist
    return response.json()
  File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)

This is the code the error should be coming from:

def auth(request):
    if not request.user.is_authenticated:
        isAvailible = None
        code = None
        if request.method == "POST":
            isAvailible = False
            if robloxpy.User.External.DoesNameExist(request.POST['username']) == "Unavailible":
                user = str(request.POST['username']).lower()
                data = requests.get(f'https://api.roblox.com/users/get-by-username?username={user}').json()
                print(user)
                user = data['Username']
                id = data['Id']
                desc = robloxpy.User.External.GetDescription(id)

                isAvailible = True
                user = str(request.POST['username']).lower()
                print(user)
                print(User.objects.filter(username=user))
                if User.objects.filter(username=user).exists():
                    code = User.objects.get(username=request.POST.get('username')).auth_code

                    if desc != None and User.objects.get(username=user).auth_code in desc:
                        userchange = User.objects.get(username=user)
                        userchange.auth_code = randomVerify()
                        userchange.save()
                        login(request, User.objects.get(username=user))
                        return redirect('home')
                else:
                    id = requests.get(f'https://api.roblox.com/users/get-by-username?username={user}').json()['Id']
                    created_user = User(username=user, rbx_id=id)
                    created_user.save()
                    code = created_user.auth_code

        content = {"available": isAvailible, "code": code}

        print(isAvailible)

        return render(request, 'auth.html', content)
    else:
        return redirect('dashboard')

def logout_acc(request):
    logout(request)
    return redirect('auth')

def welcome(request):
    if request.user.is_authenticated:
        id = requests.post(f'https://users.roblox.com/v1/usernames/users', data={
        "usernames": [
            request.user.username
        ],
        "excludeBannedUsers": True
        }).json()["data"][0]['id']
        avatar_uri = f"https://www.roblox.com/headshot-thumbnail/image?userId={id}&width=60&height=60&format=png"
        content = {'avatar_uri': avatar_uri}
        return render(request, 'welcome.html', content)
    else:
        return redirect('auth')


问:
Laravel groupBy a JSON column's key
I'm working with Laravel 9 and PHP 8.1, I have two models, a Product and ProductOption. Product options are joined to Products and contain an optional, nullable json field called extra where additional custom data about a product option may be stored.

I have created a bunch of product options where the extra field contains a "region" and "regions", for example:

{
    "region": "us",
    "regions": [
        "us"
    ]
}
```
<p>When performing my query to get all products, I'd like to group the joined options to my <code>Product</code> by the region, so it might end up looking something like:</p>
```{
  id: 1,
  options: [
    us: [
      {
        id: 1
      },
      {
        id: 2
      }
    ],
    eur: [
      {
        id: 1
      },
      {
        id: 2
      }
    ]
  ]
}
```
<p>This is my current query:</p>
<pre class="lang-php prettyprint-override"><code>$product = $request->input('product');
$type = $request->input('type');

$products = Product::where('slug', $product)
->where('is_enabled', true)
->with(['options' => function ($query) use ($type) {
    $query->where('is_enabled', true)
          ->whereNotNull('extra')
          ->whereJsonLength('extra->regions', 1)
          ->where('slug', 'like', "%$type%")
          ->select('extra->region as region');
}])->get();
</code>```

I was thinking I could do something like groupBy('extra->region') but this throws an error.

UPDATE

I've tried added a select() statement statement to attempt to pull out the "region" field from my JSON extra column. This returns the following error:

The attribute [product_id] either does not exist or was not retrieved for model [App\Models\ProductOption].

Title: Laravel groupBy a JSON column's key

Body:
I'm working with Laravel 9 and PHP 8.1, I have two models, a Product and ProductOption. Product options are joined to Products and contain an optional, nullable json field called extra where additional custom data about a product option may be stored.

I have created a bunch of product options where the extra field contains a "region" and "regions", for example:

{
    "region": "us",
    "regions": [
        "us"
    ]
}

When performing my query to get all products, I'd like to group the joined options to my Product by the region, so it might end up looking something like:

{
  id: 1,
  options: [
    us: [
      {
        id: 1
      },
      {
        id: 2
      }
    ],
    eur: [
      {
        id: 1
      },
      {
        id: 2
      }
    ]
  ]
}

This is my current query:

$product = $request->input('product');
$type = $request->input('type');

$products = Product::where('slug', $product)
->where('is_enabled', true)
->with(['options' => function ($query) use ($type) {
    $query->where('is_enabled', true)
          ->whereNotNull('extra')
          ->whereJsonLength('extra->regions', 1)
          ->where('slug', 'like', "%$type%")
          ->select('extra->region as region');
}])->get();

I was thinking I could do something like groupBy('extra->region') but this throws an error.

UPDATE

I've tried added a select() statement statement to attempt to pull out the "region" field from my JSON extra column. This returns the following error:

The attribute [product_id] either does not exist or was not retrieved for model [App\Models\ProductOption].