Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import pypyodbc
- import requests
- import json
- import datetime
- class ParamsToREST(object):
- """docstring"""
- def __init__(self, im):
- pass
- def __init__(self, im):
- self.headers = {
- 'Content-Type': 'application/json',
- 'Authorization': 'Basic YWxmYWNsZXZlcjpBbGZhQ2xldmVyNA=='
- }
- self.object_id = im['object_id']
- self.created = im['created']
- self.user = im['сотруднику_object_id']
- self.status = im['статус']
- pass
- def getStatus(self):
- return self.status
- def set_model_stop(self):
- return json.dumps({
- "N4": {
- "SuspendReason": "Ожидание пользователя",
- "Comment": "Нет на месте",
- "AssigneeName": self.user,
- "SuspendTime": (datetime.datetime.now() + datetime.timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%S+00:00")
- }
- },sort_keys=True)
- def set_model_start(self):
- return json.dumps({
- "N4": {
- }
- },sort_keys=True)
- def set_model_save(self):
- return json.dumps({
- "N4": {
- "AssigneeName":self.user
- }
- }, sort_keys=True)
- def set_url_stop(self):
- return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/stop"
- def set_url_start(self):
- return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/start"
- def set_url_save(self):
- return "http://sm-int.moscow.alfaintra.net/SM/9/rest/N4/"+self.object_id+"/action/save"
- def POST_method_stop(self):
- r=requests.post(self.set_url_stop(), headers=self.headers, data=self.set_model_stop())
- r.close()
- t = r.content.decode('utf8')
- sc = r.status_code
- rc = r.json()['ReturnCode']
- msg = str(r.json()['Messages'])
- print(t, sc, rc,msg)
- flag = rc == 0 and sc == 200
- info = ""
- if (flag):
- info = info
- else:
- info = t
- 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("'", "''") + "')")
- cursor.execute(SQLInsert)
- connection.commit()
- return {
- "Flag": flag,
- "method": "stop",
- "info": info
- }
- def POST_method_start(self):
- r=requests.post(self.set_url_start(), headers=self.headers, data=self.set_model_start())
- r.close()
- t=r.content.decode('utf8')
- sc = r.status_code
- rc = r.json()['ReturnCode']
- msg = str(r.json()['Messages'])
- print(t, sc, rc,msg)
- flag = rc == 0 and sc == 200
- info = ""
- if (flag):
- info = info
- else:
- info = t
- 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("'","''")+"')")
- cursor.execute(SQLInsert)
- connection.commit()
- return {
- "Flag": flag,
- "method": "start",
- "info": info
- }
- def POST_method_save(self):
- r=requests.post(self.set_url_save(), headers=self.headers, data=self.set_model_save())
- r.close()
- t = r.content.decode('utf8')
- sc = r.status_code
- rc = r.json()['ReturnCode']
- msg = str(r.json()['Messages'])
- print(t, sc,rc,msg)
- flag = rc == 0 and sc == 200
- info = ""
- if (flag):
- info = info
- else:
- info = t
- 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("'", "''") + "')")
- cursor.execute(SQLInsert)
- connection.commit()
- return {
- "Flag" : flag,
- "method": "save",
- "info": info
- }
- def callRESTSErvice(im):
- call = ParamsToREST(im)
- if call.getStatus() == ("Ожидание"):
- return(call.POST_method_save())
- elif call.getStatus() == ("Открыт"):
- issaved = call.POST_method_start()
- if (issaved['Flag']) :
- return call.POST_method_stop()
- return issaved
- else:
- return call.POST_method_stop()
- connection = pypyodbc.connect("DRIVER={SQL Server}; Server=acleverappv; UID=tech_user; pwd=tech_user;DATABASE=master;")
- cursor = connection.cursor()
- SQLQuery = (''' select [object_id],[created], [статус], [сотруднику_object_id] from [sm_authomation].[dbo].[incidents] where STATUS = 'TO_SM' ''')
- cursor.execute(SQLQuery)
- result = cursor.fetchall()
- if result == []:
- print('Нет нераспределенных инцидентов в БД')
- else: print(result)
- print('items is')
- for item in result:
- print(item)
- result = callRESTSErvice(item)
- print(result)
- if (result['Flag']):
- print("success")
- else: print('error')
- cursor.close()
- connection.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement