Преглед изворни кода

refactor: updated the ANAF endpoint version and fixed some issue regarding the new format; Removed support for Python2

Alex Gheorghita пре 1 година
родитељ
комит
581677a4d6
3 измењених фајлова са 50 додато и 84 уклоњено
  1. 29 59
      pyAnaf/api.py
  2. 11 12
      pyAnaf/console.py
  3. 10 13
      pyAnaf/models.py

+ 29 - 59
pyAnaf/api.py

@@ -1,32 +1,7 @@
-from __future__ import unicode_literals, print_function
-
 import datetime
 import datetime
-import sys
-
-PY_3_OR_HIGHER = sys.version_info >= (3, 0)
-
-try:
-    import urllib.request as urllib_request
-    import urllib.error as urllib_error
-except ImportError:
-    import urllib2 as urllib_request
-    import urllib2 as urllib_error
-
-try:
-    from cStringIO import StringIO
-except ImportError:
-    from io import BytesIO as StringIO
-
-try:
-    import http.client as http_client
-except ImportError:
-    import httplib as http_client
-
-try:
-    import json
-except ImportError:
-    import simplejson as json
-
+import json
+import urllib.request as urllib_request
+import urllib.error as urllib_error
 from .models import AnafResultEntry
 from .models import AnafResultEntry
 
 
 
 
@@ -35,6 +10,7 @@ class AnafError(Exception):
     Base Exception thrown by the Anaf object when there is a
     Base Exception thrown by the Anaf object when there is a
     general error interacting with the API.
     general error interacting with the API.
     """
     """
+
     pass
     pass
 
 
 
 
@@ -43,6 +19,7 @@ class AnafHTTPError(Exception):
     Exception thrown by the Anaf object when there is an
     Exception thrown by the Anaf object when there is an
     HTTP error interacting with anaf.ro.
     HTTP error interacting with anaf.ro.
     """
     """
+
     pass
     pass
 
 
 
 
@@ -51,13 +28,14 @@ class AnafResponseError(Exception):
     Exception thrown by the Anaf object when there is an
     Exception thrown by the Anaf object when there is an
     error the response returned from ANAF.
     error the response returned from ANAF.
     """
     """
+
     pass
     pass
 
 
 
 
-class Anaf(object):
+class Anaf:
     WS_ENDPOINTS = {
     WS_ENDPOINTS = {
-        'sync': 'https://webservicesp.anaf.ro/PlatitorTvaRest/api/v3/ws/tva',
-        'async': 'https://webservicesp.anaf.ro/AsynchWebService/api/v3/ws/tva'
+        "sync": "https://webservicesp.anaf.ro/PlatitorTvaRest/api/v8/ws/tva",
+        "async": "https://webservicesp.anaf.ro/AsynchWebService/api/v8/ws/tva",
     }
     }
     LIMIT = 500
     LIMIT = 500
 
 
@@ -69,38 +47,35 @@ class Anaf(object):
     @staticmethod
     @staticmethod
     def _validate_cui(cui):
     def _validate_cui(cui):
         if not isinstance(cui, int):
         if not isinstance(cui, int):
-            raise AnafError('CUI should be integer')
+            raise AnafError("CUI should be integer")
 
 
     @staticmethod
     @staticmethod
     def _validate_date(date):
     def _validate_date(date):
         if not isinstance(date, datetime.date):
         if not isinstance(date, datetime.date):
-            raise AnafError('Date should be of type datetime.date')
+            raise AnafError("Date should be of type datetime.date")
 
 
     @staticmethod
     @staticmethod
     def _prepare_data(data):
     def _prepare_data(data):
-        if PY_3_OR_HIGHER:
-            return bytes(data, 'utf-8')
-        else:
-            return data
+        return bytes(data, "utf-8")
 
 
-    def addEndpoint(self, url, target='sync'):
-        if target not in ['sync', 'async']:
-            raise AnafError('Invalid target for endpoint. Must be one of \'sync\' or \'async\'')
+    def addEndpoint(self, url, target="sync"):
+        if target not in ["sync", "async"]:
+            raise AnafError("Invalid target for endpoint. Must be one of 'sync' or 'async'")
 
 
-        self.WS_ENDPOINTS[target] = url;
+        self.WS_ENDPOINTS[target] = url
 
 
     def setLimit(self, limit):
     def setLimit(self, limit):
         try:
         try:
             self.LIMIT = int(limit)
             self.LIMIT = int(limit)
         except:
         except:
-            raise AnafError('Limit should be an integer')
+            raise AnafError("Limit should be an integer")
 
 
     def setCUIList(self, cui_list=[], date=None):
     def setCUIList(self, cui_list=[], date=None):
         if date is None:
         if date is None:
             date = datetime.date.today()
             date = datetime.date.today()
 
 
         if len(cui_list) > self.LIMIT:
         if len(cui_list) > self.LIMIT:
-            raise AnafError('Too many CUIs to be queried. Should limit to %d' % self.LIMIT)
+            raise AnafError("Too many CUIs to be queried. Should limit to %d" % self.LIMIT)
 
 
         self._validate_date(date)
         self._validate_date(date)
         for cui in cui_list:
         for cui in cui_list:
@@ -116,43 +91,38 @@ class Anaf(object):
 
 
         self.cuis[cui] = date
         self.cuis[cui] = date
         if len(self.cuis.items()) > self.LIMIT:
         if len(self.cuis.items()) > self.LIMIT:
-            raise AnafError('Too many CUIs to be queried. Should limit to %d' % self.LIMIT)
+            raise AnafError("Too many CUIs to be queried. Should limit to %d" % self.LIMIT)
 
 
     def Request(self):
     def Request(self):
         # translate cuis entries to ANAF json format
         # translate cuis entries to ANAF json format
         cui_list = []
         cui_list = []
         for entry in self.cuis.items():
         for entry in self.cuis.items():
-            cui_list.append(
-                {
-                    'cui': entry[0],
-                    'data': entry[1].isoformat()
-                }
-            )
+            cui_list.append({"cui": entry[0], "data": entry[1].isoformat()})
 
 
-        request = urllib_request.Request(self.WS_ENDPOINTS['sync'])
-        request.add_header('Content-Type', 'application/json')
+        request = urllib_request.Request(self.WS_ENDPOINTS["sync"])
+        request.add_header("Content-Type", "application/json")
 
 
         try:
         try:
             response = urllib_request.urlopen(request, self._prepare_data(json.dumps(cui_list)))
             response = urllib_request.urlopen(request, self._prepare_data(json.dumps(cui_list)))
         except urllib_error.HTTPError as e:
         except urllib_error.HTTPError as e:
-            raise AnafHTTPError('Error connecting to ANAF. Got a %d HTTP code.' % e.code)
+            raise AnafHTTPError("Error connecting to ANAF. Got a %d HTTP code." % e.code)
 
 
         data = response.read()
         data = response.read()
         if isinstance(data, bytes):
         if isinstance(data, bytes):
-            data = data.decode('utf-8')
+            data = data.decode("utf-8")
         try:
         try:
             result = json.loads(data)
             result = json.loads(data)
         except:
         except:
-            raise AnafResponseError('Error parsing json response from ANAF.')
+            raise AnafResponseError("Error parsing json response from ANAF.")
 
 
-        if result['cod'] != 200:
-            raise AnafResponseError('%s' % result['message'])
+        if result["cod"] != 200:
+            raise AnafResponseError("%s" % result["message"])
 
 
-        result = result['found']
+        result = result["found"]
         self.result = result
         self.result = result
 
 
         for entry in result:
         for entry in result:
-            self.entries[entry['cui']] = AnafResultEntry(entry)
+            self.entries[entry["date_generale"]["cui"]] = AnafResultEntry(entry)
 
 
     def getCUIData(self, cui):
     def getCUIData(self, cui):
         if cui not in self.entries.keys():
         if cui not in self.entries.keys():

+ 11 - 12
pyAnaf/console.py

@@ -1,6 +1,4 @@
 # coding: utf-8
 # coding: utf-8
-
-from __future__ import print_function
 import sys
 import sys
 import os
 import os
 import datetime
 import datetime
@@ -10,30 +8,30 @@ import pprint
 try:
 try:
     from pyAnaf.api import Anaf
     from pyAnaf.api import Anaf
 except:
 except:
-    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
+    sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
     from pyAnaf.api import Anaf
     from pyAnaf.api import Anaf
 
 
 
 
-class MyPrettyPrinter(pprint.PrettyPrinter):
+class CustomPrettyPrinter(pprint.PrettyPrinter):
     def format(self, object, context, maxlevels, level):
     def format(self, object, context, maxlevels, level):
-        #print (type(object))
-        #print (object)
+        # print (type(object))
+        # print (object)
         # if isinstance(object, str):
         # if isinstance(object, str):
         #     return (object.encode('utf8'), True, False)
         #     return (object.encode('utf8'), True, False)
         return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
         return pprint.PrettyPrinter.format(self, object, context, maxlevels, level)
 
 
+
 def print_err(*args, **kwargs):
 def print_err(*args, **kwargs):
     print(*args, file=sys.stderr, **kwargs)
     print(*args, file=sys.stderr, **kwargs)
 
 
+
 def main():
 def main():
     if len(sys.argv) < 2:
     if len(sys.argv) < 2:
         print_err("usage: %s <cuis_separated_by_comma> <limit>\n" % sys.argv[0])
         print_err("usage: %s <cuis_separated_by_comma> <limit>\n" % sys.argv[0])
         sys.exit(-255)
         sys.exit(-255)
 
 
     limit = 5
     limit = 5
-
-    cuis = sys.argv[1].split(',')
-
+    cuis = sys.argv[1].split(",")
 
 
     try:
     try:
         limit = int(sys.argv[2])
         limit = int(sys.argv[2])
@@ -41,9 +39,9 @@ def main():
         pass
         pass
 
 
     today = datetime.date.today()
     today = datetime.date.today()
-
     anaf = Anaf()
     anaf = Anaf()
     anaf.setLimit(limit)
     anaf.setLimit(limit)
+
     for cui in cuis:
     for cui in cuis:
         try:
         try:
             anaf.addCUI(int(cui), date=today)
             anaf.addCUI(int(cui), date=today)
@@ -51,10 +49,11 @@ def main():
             print_err(e)
             print_err(e)
 
 
     anaf.Request()
     anaf.Request()
+    pp = CustomPrettyPrinter(indent=4)
 
 
-    pp = MyPrettyPrinter(indent=4)
     for entry in anaf.result:
     for entry in anaf.result:
         pp.pprint(entry)
         pp.pprint(entry)
 
 
-if __name__ == '__main__':
+
+if __name__ == "__main__":
     main()
     main()

+ 10 - 13
pyAnaf/models.py

@@ -1,16 +1,13 @@
-
-class AnafResultEntry(object):
-
+class AnafResultEntry:
     def __init__(self, result):
     def __init__(self, result):
-        self.cui = result['cui']
-        self.date = result['data']
-        self.is_active = not result['statusInactivi']
-        self.name = result['denumire']
-        self.address = result['adresa']
-        self.vat_eligible = result['scpTVA']
-        self.vat_split_eligible = result['statusSplitTVA']
-        self.vat_collection_eligible = result['statusTvaIncasare']
-
+        self.cui = result["date_generale"]["cui"]
+        self.date = result["date_generale"]["data"]
+        self.is_active = not result["stare_inactiv"]["statusInactivi"]
+        self.name = result["date_generale"]["denumire"]
+        self.address = result["date_generale"]["adresa"]
+        self.vat_eligible = result["inregistrare_scop_Tva"]["scpTVA"]
+        self.vat_split_eligible = result["inregistrare_SplitTVA"]["statusSplitTVA"]
+        self.vat_collection_eligible = result["inregistrare_RTVAI"]["statusTvaIncasare"]
 
 
     def __str__(self):
     def __str__(self):
-        return "CUI: %s, Name: %s" % (self.cui,self.name)
+        return "CUI: %s, Name: %s" % (self.cui, self.name)