Advertisement
Guest User

Untitled

a guest
Apr 4th, 2020
255
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.51 KB | None | 0 0
  1. import pypyodbc
  2. import requests
  3. import json
  4. import datetime
  5.  
  6.  
  7. class ParamsToREST(object):
  8.     """docstring"""
  9.     def __init__(self, im):
  10.         pass
  11.  
  12.     def __init__(self, im):
  13.         self.headers = {
  14.             'Content-Type': 'application/json',
  15.             'Authorization': 'Basic YWxmYWNsZXZlcjpBbGZhQ2xldmVyNA=='
  16.         }
  17.         self.object_id = im['object_id']
  18.         self.created = im['created']
  19.         self.user = im['сотруднику_object_id']
  20.         self.status = im['статус']
  21.         pass
  22.  
  23.     def getStatus(self):
  24.         return self.status
  25.  
  26.     def set_model_stop(self):
  27.         return json.dumps({
  28.             "N4": {
  29.                 "SuspendReason": "Ожидание пользователя",
  30.                 "Comment": "Нет на месте",
  31.                 "AssigneeName": self.user,
  32.                 "SuspendTime": (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
  33.             }
  34.         },sort_keys=True)
  35.  
  36.     def set_model_start(self):
  37.         return json.dumps({
  38.             "N4": {
  39.             }
  40.         },sort_keys=True)
  41.  
  42.     def set_model_save(self):
  43.         return json.dumps({
  44.                     "N4": {
  45.                         "AssigneeName":self.user
  46.                     }
  47.                }, sort_keys=True)
  48.  
  49.     def set_url_stop(self):
  50.         return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/stop"
  51.  
  52.     def set_url_start(self):
  53.         return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/start"
  54.  
  55.     def set_url_save(self):
  56.         return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/save"
  57.  
  58.     def POST_method_stop(self):
  59.         r=requests.post(self.set_url_stop(), headers=self.headers, data=self.set_model_stop())
  60.         r.close()
  61.         t = r.content.decode('utf8')
  62.         sc = r.status_code
  63.         rc = r.json()['ReturnCode']
  64.         msg = str(r.json()['Messages'])
  65.         print(t, sc, rc,msg)
  66.         flag = rc == 0 and sc == 200
  67.         info = ""
  68.         if (flag):
  69.             info = info
  70.         else:
  71.             info = t
  72.             SQLInsert = ("insert into [sm_authomation].[dbo].[Logs] (Object_ID, Date , Request, Response, Message  ) values ('" + self.object_id + "', GETDATE(), '"+str(json.loads(self.set_model_stop())).replace("'", "''")+"', '" + str(rc) + "','" + msg.replace("'", "''") + "')")
  73.             cursor.execute(SQLInsert)
  74.             connection.commit()
  75.         return {
  76.             "Flag": flag,
  77.             "method": "stop",
  78.             "info": info
  79.         }
  80.  
  81.     def POST_method_start(self):
  82.         r=requests.post(self.set_url_start(), headers=self.headers, data=self.set_model_start())
  83.         r.close()
  84.         t=r.content.decode('utf8')
  85.         sc = r.status_code
  86.         rc = r.json()['ReturnCode']
  87.         msg = str(r.json()['Messages'])
  88.         print(t, sc, rc,msg)
  89.         flag = rc == 0 and sc == 200
  90.         info = ""
  91.         if (flag):
  92.             info = info
  93.         else:
  94.             info = t
  95.             SQLInsert = ("insert into [sm_authomation].[dbo].[Logs] (Object_ID, Date , Request, Response, Message  ) values ('"+self.object_id+"', GETDATE(), '"+str(json.loads(self.set_model_start())).replace("'", "''")+"', '"+str(rc)+"','"+ msg.replace("'","''")+"')")
  96.             cursor.execute(SQLInsert)
  97.             connection.commit()
  98.         return {
  99.             "Flag": flag,
  100.             "method": "start",
  101.             "info": info
  102.         }
  103.  
  104.     def POST_method_save(self):
  105.         r=requests.post(self.set_url_save(), headers=self.headers, data=self.set_model_save())
  106.         r.close()
  107.         t = r.content.decode('utf8')
  108.         sc = r.status_code
  109.         rc = r.json()['ReturnCode']
  110.         msg = str(r.json()['Messages'])
  111.         print(t, sc,rc,msg)
  112.         flag = rc == 0 and sc == 200
  113.         info = ""
  114.         if (flag):
  115.             info = info
  116.         else:
  117.             info = t
  118.             SQLInsert = ("insert into [sm_authomation].[dbo].[Logs] (Object_ID, Date , Request, Response, Message  ) values ('" + self.object_id + "', GETDATE(), '"+str(json.loads(self.set_model_save())).replace("'", "''")+"', '" + str(rc) + "','" + msg.replace("'", "''") + "')")
  119.             cursor.execute(SQLInsert)
  120.             connection.commit()
  121.         return  {
  122.             "Flag" : flag,
  123.             "method": "save",
  124.             "info": info
  125.         }
  126.  
  127.  
  128.  
  129. def callRESTSErvice(im):
  130.     call = ParamsToREST(im)
  131.     if call.getStatus() == ("Ожидание"):
  132.         return(call.POST_method_save())
  133.     elif call.getStatus() == ("Открыт"):
  134.         issaved = call.POST_method_start()
  135.         if (issaved['Flag']) :
  136.             return call.POST_method_stop()
  137.         return issaved
  138.     else:
  139.         return call.POST_method_stop()
  140.  
  141.  
  142.  
  143. connection = pypyodbc.connect("DRIVER={SQL Server}; Server=acleverappv; UID=tech_user; pwd=tech_user;DATABASE=master;")
  144. cursor = connection.cursor()
  145. SQLQuery = ('''   select  [object_id],[created], [статус], [сотруднику_object_id] from [sm_authomation].[dbo].[incidents] where STATUS = 'TO_SM'  ''')
  146. cursor.execute(SQLQuery)
  147. result = cursor.fetchall()
  148.  
  149.  
  150. if result == []:
  151.     print('Нет нераспределенных инцидентов в БД')
  152. else: print(result)
  153.  
  154.  
  155. print('items is')
  156. for item in result:
  157.     print(item)
  158.     result = callRESTSErvice(item)
  159.     print(result)
  160.     if (result['Flag']):
  161.         print("success")
  162.     else: print('error')
  163.  
  164. cursor.close()
  165. connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement