Home > Software design >  Code works incorrectly after Exception - even with loop/try except etc
Code works incorrectly after Exception - even with loop/try except etc

Time:01-21

I'm trying to make decoder, data-->json. You paste raw data, and it decodes it into json. Here are 2 scenarios:

  1. FIRST input is a correct data, it then correctly decodes it into json.
  2. FIRST input is random string, like "abcd" - code then says that data is invalid.

After second scenario, even when you try to put VALID data, it will say "invalid data" forever. How can make it work, so when you first write "abcd", and then paste valid data, it will just decode it?! I tried loops, breaks, continues... Nothing works, and typing invalid input ruins whole code - you have to restart program and paste VALID data.

import requests
import json

while True:
    try:
        raw = input('Please paste raw data: ' "\n")
        url = 'https://platform.lobaro.com/api/mbus?raw={}'.format(raw)
        print("\n")

        get = requests.get(url)
        json_body = get.json()

        parsed = json.dumps(json_body)
        parsed2 = json.loads(parsed)
        
        formatted = json.dumps(json.loads(parsed), indent=2)
        print(formatted "\n")

        print("INFORMATIONS:")
        name = parsed2["MFieldLongString"]
        print(f'Producer: {name}')

        l1 = parsed2["Length"]
        print(f'Lenght: {l1}' '\n')
        print('============================================================================')
        
    except requests.exceptions.JSONDecodeError:
        print('Invalid data! Could not parse to JSON.' "\n")
        continue

CodePudding user response:

The site uses other API URL to decode wmbus messages:

import json
import requests

api_url = "https://platform.lobaro.com/gqlgen/query"
payload = {
    "operationName": None,
    "query": "query ($raw: String!, $key: String) {\n  wmbus: parseWmbus(raw: $raw, key: $key) {\n    data\n    parseError\n    __typename\n  }\n}\n",
    "variables": {
        "key": "0102030405060708090A0B0C0D0E0F11",   # <-- change this field
        "raw": "2e44931578563412330333637a2a0020055923c95aaa26d1b2e7493b2a8b013ec4a6f6d3529b520edff0ea6defc955b29d6d69ebf3ec8a",   # <-- change this field
    },
}

data = requests.post(api_url, json=payload).json()
if data['data']['wmbus']['parseError'] == "":
    data = json.loads(data["data"]["wmbus"]["data"])
    print(data)

Prints:

{
    "Raw": "0x2e4493157856341233037a2a0020055923c95aaa26d1b2e7493b013ec4a6f6d3529b520edff0ea6defc99d6d69ebf3",
    "RawWithCrc": "0x2e44931578563412330333637a2a0020055923c95aaa26d1b2e7493b2a8b013ec4a6f6d3529b520edff0ea6defc955b29d6d69ebf3ec8a",
    "FrameFormat": "A",
    "Length": 46,
    "CField": "0x44",
    "CFieldString": "0x44 (SND_NR)",
    "MField": "0x9315",
    "MFieldCodeString": "ELS",
    "MFieldLongString": "Elster GmbH, Germany, Europe",
    "Id": 305419896,
    "IdString": "12345678",
    "Version": 51,
    "Device": "0x03",
    "DeviceString": "Gas",
    "CiField": "0x7a",
    "HeaderKnown": True,
    "PayloadKnown": True,
    "CrcValid": True,
    "HasCrc": True,
    "SourceType": "WMBUS",
    "IsCompactFrame": False,
    "FormatSignature": 61330,
    "FormatFrame": "0x0c14046d02fd17",
    "Header": {
        "Serial": 0,
        "IdString": "",
        "ManufacturerCode": 0,
        "MFieldCodeString": "",
        "MFieldLongString": "",
        "Version": 0,
        "DeviceType": "0x00",
        "DeviceString": "",
        "EncryptionMode": 5,
        "EncryptionModeString": "AES with CBC",
        "EncryptedBlocks": 2,
        "HopCount": 0,
        "IsAccessible": True,
        "IsBidirectionalMode": False,
        "IsSynchronous": False,
        "ReservedBit": False,
        "TelegramType": 0,
        "AccessNumber": 42,
        "StatusByte": 0,
        "ConfigField": [32, 5],


...and so on.

CodePudding user response:

This is because the response could have been cached. One way to disable the caching is to pass the appropriate headers in the request. Something like

get = requests.get(url, headers={
                          'Cache-Control': 'no-cache', 
                          'Pragma': 'no-cache', 
                          'Expires': '0' })

See 'Pedro Lobitos' answer to this question here for a good explanation here How do I clear cache with Python Requests?. (Good explanation and very good discussion/comments too)

CodePudding user response:

You could try to restart a method after the Exception, so you delete all local variables temporarily and restart from scratch:

import gc
def myMethod():
    gc.collect(generation=2)
    while True:
        try:
            raw = input('Please paste raw data: ' "\n")
            url = 'https://platform.lobaro.com/api/mbus?raw={}'.format(raw)
            print("\n")

            get = requests.get(url)
            json_body = get.json()

            parsed = json.dumps(json_body)
            parsed2 = json.loads(parsed)
    
            formatted = json.dumps(json.loads(parsed), indent=2)
            print(formatted "\n")

            print("INFORMATIONS:")
            name = parsed2["MFieldLongString"]
            print(f'Producer: {name}')

            l1 = parsed2["Length"]
            print(f'Lenght: {l1}' '\n')
            print('=====')
    
        except requests.exceptions.JSONDecodeError:
            print('Invalid data! Could not parse to JSON.' "\n")
            break

    myMethod()

So everytime it raises an Exception, the "old execution" is killed and a new one starts. The gc is there for automatically garbage-collect the leftovers from the old execution.

  • Related