#RobotDB prefinal

dev-linux
Ivan Maslov 5 years ago
parent 029a5ce67d
commit fb3e122783

@ -0,0 +1,11 @@
import win32com.client as win32
def OpenWorkbook(xlapp, xlfile):
try:
xlwb = xlapp.Workbooks(xlfile)
except Exception as e:
try:
xlwb = xlapp.Workbooks.Open(xlfile)
except Exception as e:
print(e)
xlwb = None
return(xlwb)

@ -14,10 +14,6 @@ $(document).ready(function() {
success: null, success: null,
dataType: "html" dataType: "html"
}); });
SQLInsert
data: [{"TableName":"",RowDict:{"Key1":Value1, "Key2":Value2}}] data: [{"TableName":"",RowDict:{"Key1":Value1, "Key2":Value2}}]
$(document).ready(function() { $(document).ready(function() {
@ -25,9 +21,42 @@ $(document).ready(function() {
$("#myid").addClass("highlight"); $("#myid").addClass("highlight");
$.ajax({ $.ajax({
type: "POST", type: "POST",
url: "http://localhost:81/", url: "http://localhost:8081/",
data: '[{"TableName":"Test", "RowDict":{"Name":"Name1","Description":"DescTest", "Money":100, "Date":"01.01.2020"}}]', data: '[{"TableName":"Test", "RowDict":{"Name":"Name1","Description":"DescTest", "Money":100, "Date":"01.01.2020"}}]',
success: null, success: null,
dataType: "html" dataType: "html"
}); });
}); });
/SQLInsert
POST
Result: json
{
"Status":"OK"|"ERROR", #General status (OK or Error in general alg)
"ErrorMessage":"", #Error message if Status = ERROR
"Result":[
{
"Status":"OK"|"ERROR", #Row status (OK or Error in current insert)
"ErrorMessage":"", #Error message if Status = ERROR
},
{}
]
}
/SQLExportXLS.xlsx
POST
Args: {
"XLSTemplatePath":"C:\\Path\\To\\XLS template.xlsx",
"XLSSheetName":"SheetName",
"OffsetRow": 2,
"OffsetCol":1,
"XLSResultPath": "C:\\Path\\To\\XLS Result.xlsx",
"XLSResultFlagSendInResponse": true,
"XLSResultFlagDeleteAfterSend": true
}
Result: xls file

@ -1,59 +1,150 @@
import json import json
from . import ExcelCom
import os
import sqlite3
import win32com.client
import time
import pythoncom
#Insert in DB #Insert in DB
def SQLInsert(inRequest,inGlobalDict): def SQLInsert(inRequest,inGlobalDict):
inResponseDict = inRequest.OpenRPAResponseDict inResponseDict = inRequest.OpenRPAResponseDict
# Create result JSON # Create result JSON
lResultJSON = {"FlagSQLInsert": False} lResultJSON = {"Status": "OK", "ErrorMessage":"", "Result":[]}
#Read the body #Set status code 200
#ReadRequest inResponseDict["StatusCode"] = 200
lInputJSON={} try:
if inRequest.headers.get('Content-Length') is not None: #Read the body
lInputByteArrayLength = int(inRequest.headers.get('Content-Length')) #ReadRequest
lInputByteArray=inRequest.rfile.read(lInputByteArrayLength) lInputJSON={}
print(lInputByteArray.decode('utf8')) if inRequest.headers.get('Content-Length') is not None:
#Превращение массива байт в объект lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputJSON=json.loads(lInputByteArray.decode('utf8')) lInputByteArray=inRequest.rfile.read(lInputByteArrayLength)
######################################## #print(lInputByteArray.decode('utf8'))
print(lInputJSON) #Превращение массива байт в объект
import sqlite3 lInputJSON=json.loads(lInputByteArray.decode('utf8'))
########################################
conn = sqlite3.connect(inGlobalDict["SQLite"]["DBPath"])
c = conn.cursor()
# Loop for rows
for lRowItem in lInputJSON:
lRowResult={"Status": "OK", "ErrorMessage":""}
try:
my_dict = lRowItem["RowDict"]
# Insert a row of data
columns = ', '.join(my_dict.keys())
placeholders = ':'+', :'.join(my_dict.keys())
query = f'INSERT INTO {lRowItem["TableName"]} (%s) VALUES (%s)' % (columns, placeholders)
c.execute(query, my_dict)
except Exception as e:
lRowResult["Status"]="ERROR"
lRowResult["ErrorMessage"]=str(e)
finally:
lResultJSON["Result"].append(lRowResult)
# Save (commit) the changes
conn.commit()
# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()
except Exception as e:
lResultJSON["Status"]="ERROR"
lResultJSON["ErrorMessage"]=str(e)
finally:
########################################
# Send message back to client
message = json.dumps(lResultJSON)
print(message)
# Write content as utf-8 data
inResponseDict["Body"] = bytes(message, "utf8")
################################################
#Export SQLite to Excel
def SQLExportXLS(inRequest,inGlobalDict):
#Step 1 - read SQLite
conn = sqlite3.connect(inGlobalDict["SQLite"]["DBPath"]) conn = sqlite3.connect(inGlobalDict["SQLite"]["DBPath"])
c = conn.cursor() c = conn.cursor()
# Loop for rows # Loop for rows
for lRowItem in lInputJSON: # for lRowItem in lInputJSON:
my_dict = lRowItem["RowDict"] # my_dict = lRowItem["RowDict"]
# Insert a row of data # # Insert a row of data
columns = ', '.join(my_dict.keys()) # columns = ', '.join(my_dict.keys())
placeholders = ':'+', :'.join(my_dict.keys()) # placeholders = ':'+', :'.join(my_dict.keys())
query = f'INSERT INTO {lRowItem["TableName"]} (%s) VALUES (%s)' % (columns, placeholders) query = f'select * from Test'
c.execute(query, my_dict) #create data array
# Save (commit) the changes #row = range(0,10)
conn.commit() i = 0
data_array = []
for row in c.execute(query):
# use the cursor as an iterable
data_array.append(row)
i += 1
# We can also close the connection if we are done with it. # We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost. # Just be sure any changes have been committed or they will be lost.
conn.close() conn.close()
######################################## #step 2 - insert in XLS
# Send message back to client pythoncom.CoInitialize()
message = json.dumps(lResultJSON) #write the array to an excel file
# Write content as utf-8 data #excel = win32com.client.Dispatch("Excel.Application")
inResponseDict["Body"] = bytes(message, "utf8") excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
excel.Visible = True
def GetScreenshot(inRequest,inGlobalDict): excel.DisplayAlerts = False
# Get Screenshot #excel.ScreenUpdating = False
def SaveScreenshot(inFilePath): #book = excel.Workbooks.Add()
# grab fullscreen #sheet = book.Worksheets(1)
# Save the entire virtual screen as a PNG #Read input JSON
lScreenshot = getScreenAsImage() lInputJSON={}
lScreenshot.save('screenshot.png', format='png') if inRequest.headers.get('Content-Length') is not None:
# lScreenshot = ScreenshotSecondScreen.grab_screen() lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
# save image file lInputByteArray=inRequest.rfile.read(lInputByteArrayLength)
# lScreenshot.save('screenshot.png') #print(lInputByteArray.decode('utf8'))
# Сохранить файл на диск #Превращение массива байт в объект
SaveScreenshot("Screenshot.png") lInputJSON=json.loads(lInputByteArray.decode('utf8'))
lFileObject = open("Screenshot.png", "rb") #Config
# Write content as utf-8 data lOffsetRow = lInputJSON["OffsetRow"]
inRequest.OpenRPAResponseDict["Body"] = lFileObject.read() lOffsetCol = lInputJSON["OffsetCol"]
# Закрыть файловый объект lXLSTemplatePath = lInputJSON["XLSTemplatePath"]
lFileObject.close() lXLSSheetName = lInputJSON["XLSSheetName"]
lXLSResultPath = lInputJSON["XLSResultPath"]
lXLSResultFlagSendInResponse = lInputJSON["XLSResultFlagSendInResponse"]
lXLSResultFlagDeleteAfterSend = lInputJSON["XLSResultFlagDeleteAfterSend"]
try:
#excel = win32com.client.gencache.EnsureDispatch('Excel.Application')
book = ExcelCom.OpenWorkbook(excel, lXLSTemplatePath)
sheet = book.Worksheets(lXLSSheetName)
excel.Visible = True
#single loop, writing a row to a range
#Logic
start = time.time()
row = 0
for line in data_array:
row += 1
sheet.Range(sheet.Cells(row+lOffsetRow,1+lOffsetCol), sheet.Cells(row+lOffsetRow, len(line)+lOffsetCol)).Value = line
if lXLSResultPath:
book.SaveAs(Filename = lXLSResultPath)
#excel.ScreenUpdating = True
except Exception as e:
print(e)
finally:
# RELEASES RESOURCES
sheet = None
book = None
excel.DisplayAlerts = True
excel.Quit()
excel = None
pythoncom.CoUninitialize()
#####################
#Step 3 - Send file content to client
#####################
if lXLSResultFlagSendInResponse and lXLSResultPath:
lFileObject = open(lXLSResultPath, "rb")
# Write content as utf-8 data
inRequest.OpenRPAResponseDict["Body"] = lFileObject.read()
# Закрыть файловый объект
lFileObject.close()
#####################
#Step 4 - Delete after send
#####################
if lXLSResultFlagDeleteAfterSend and lXLSResultPath:
if os.path.exists(lXLSResultPath):
os.remove(lXLSResultPath)
def SettingsUpdate(inGlobalConfiguration): def SettingsUpdate(inGlobalConfiguration):
import os import os
import pyOpenRPA.Orchestrator import pyOpenRPA.Orchestrator
@ -70,8 +161,8 @@ def SettingsUpdate(inGlobalConfiguration):
# "ResponseDefRequestGlobal": None #Function with str result # "ResponseDefRequestGlobal": None #Function with str result
#} #}
#Orchestrator basic dependencies #Orchestrator basic dependencies
{"Method":"POST", "URL": "/", "MatchType": "EqualCase", "ResponseDefRequestGlobal": SQLInsert, "ResponseContentType": "text/html"}, {"Method":"POST", "URL": "/SQLInsert", "MatchType": "EqualCase", "ResponseDefRequestGlobal": SQLInsert, "ResponseContentType": "application/json"},
{"Method":"GET", "URL": "/3rdParty/Semantic-UI-CSS-master/semantic.min.css", "MatchType": "EqualCase", "ResponseFilePath": os.path.join(lOrchestratorFolder, "..\\Resources\\Web\\Semantic-UI-CSS-master\\semantic.min.css"), "ResponseContentType": "text/css"} {"Method":"POST", "URL": "/SQLExportXLS.xlsx", "MatchType": "EqualCase", "ResponseDefRequestGlobal": SQLExportXLS, "ResponseContentType": "application/octet-stream"}
] ]
inGlobalConfiguration["Server"]["URLList"]=inGlobalConfiguration["Server"]["URLList"]+lURLList inGlobalConfiguration["Server"]["URLList"]=inGlobalConfiguration["Server"]["URLList"]+lURLList
return inGlobalConfiguration return inGlobalConfiguration

@ -3,7 +3,7 @@ r"""
The OpenRPA package (from UnicodeLabs) The OpenRPA package (from UnicodeLabs)
""" """
__version__ = 'v1.0.37' __version__ = 'v1.0.38'
__all__ = [] __all__ = []
__author__ = 'Ivan Maslov <ivan.maslov@unicodelabs.ru>' __author__ = 'Ivan Maslov <ivan.maslov@unicodelabs.ru>'
#from .Core import Robot #from .Core import Robot

Binary file not shown.

@ -14,16 +14,16 @@ def Settings():
}, },
"Server": { "Server": {
"ListenPort_": "Порт, по которому можно подключиться к демону", "ListenPort_": "Порт, по которому можно подключиться к демону",
"ListenPort": 81, "ListenPort": 8081,
"ListenURLList": [ "ListenURLList": [
{ {
"Description": "Local machine test", "Description": "Local machine test",
"URL_": "Сетевое расположение сервера демона", "URL_": "Сетевое расположение сервера демона",
"URL": "http://127.0.0.1:81" "URL": "http://127.0.0.1:8081"
} }
], ],
"AccessUsers": { #Default - all URL is blocked "AccessUsers": { #Default - all URL is blocked
"FlagCredentialsAsk": True, #Turn on Authentication "FlagCredentialsAsk": False, #Turn on Authentication
"RuleDomainUserDict": { "RuleDomainUserDict": {
#("DOMAIN", "USER"): { !!!!!only in upper case!!!! #("DOMAIN", "USER"): { !!!!!only in upper case!!!!
# "MethodMatchURLBeforeList": [ # "MethodMatchURLBeforeList": [

Binary file not shown.
Loading…
Cancel
Save