Commit 029a5ce6 authored by Ivan Maslov's avatar Ivan Maslov

#RobotDB (Web <SQLIte>) Insert + XLS export (XLSName, SheetName, FlagExportHeader)

parent 74c355f6
https://www.tutorialspoint.com/online_jquery_editor.php
<title>Try jQuery Online</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
$.ajax({
type: "POST",
url: "http://localhost:81/",
data: '{"data":1}',
success: null,
dataType: "html"
});
SQLInsert
data: [{"TableName":"",RowDict:{"Key1":Value1, "Key2":Value2}}]
$(document).ready(function() {
$("em").addClass("selected");
$("#myid").addClass("highlight");
$.ajax({
type: "POST",
url: "http://localhost:81/",
data: '[{"TableName":"Test", "RowDict":{"Name":"Name1","Description":"DescTest", "Money":100, "Date":"01.01.2020"}}]',
success: null,
dataType: "html"
});
});
\ No newline at end of file
import subprocess
import json
import datetime
import time
import codecs
import os
import signal
import sys #Get input argument
import pdb
from . import Server
import logging
import copy
#from .Settings import Settings
import importlib
from importlib import util
#Единый глобальный словарь (За основу взять из Settings.py)
global mGlobalDict
#Call Settings function from argv[1] file
################################################
lSubmoduleFunctionName = "Settings"
lFileFullPath = sys.argv[1]
lModuleName = (lFileFullPath.split("\\")[-1])[0:-3]
lTechSpecification = importlib.util.spec_from_file_location(lModuleName, lFileFullPath)
lTechModuleFromSpec = importlib.util.module_from_spec(lTechSpecification)
lTechSpecificationModuleLoader = lTechSpecification.loader.exec_module(lTechModuleFromSpec)
mGlobalDict = None
if lSubmoduleFunctionName in dir(lTechModuleFromSpec):
# Run SettingUpdate function in submodule
mGlobalDict = getattr(lTechModuleFromSpec, lSubmoduleFunctionName)()
#################################################
#mGlobalDict = Settings.Settings(sys.argv[1])
Server.mGlobalDict = mGlobalDict
#Инициализация настроечных параметров
lDaemonActivityLogDict={} #Словарь отработанных активностей, ключ - кортеж (<activityType>, <datetime>, <processPath || processName>, <processArgs>)
lDaemonStartDateTime=datetime.datetime.now()
#Инициализация сервера
lThreadServer = Server.RobotDaemonServer("ServerThread", mGlobalDict)
lThreadServer.start()
\ No newline at end of file
This diff is collapsed.
import json
#Insert in DB
def SQLInsert(inRequest,inGlobalDict):
inResponseDict = inRequest.OpenRPAResponseDict
# Create result JSON
lResultJSON = {"FlagSQLInsert": False}
#Read the body
#ReadRequest
lInputJSON={}
if inRequest.headers.get('Content-Length') is not None:
lInputByteArrayLength = int(inRequest.headers.get('Content-Length'))
lInputByteArray=inRequest.rfile.read(lInputByteArrayLength)
print(lInputByteArray.decode('utf8'))
#Превращение массива байт в объект
lInputJSON=json.loads(lInputByteArray.decode('utf8'))
########################################
print(lInputJSON)
import sqlite3
conn = sqlite3.connect(inGlobalDict["SQLite"]["DBPath"])
c = conn.cursor()
# Loop for rows
for lRowItem in lInputJSON:
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)
# 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()
########################################
# Send message back to client
message = json.dumps(lResultJSON)
# Write content as utf-8 data
inResponseDict["Body"] = bytes(message, "utf8")
def GetScreenshot(inRequest,inGlobalDict):
# Get Screenshot
def SaveScreenshot(inFilePath):
# grab fullscreen
# Save the entire virtual screen as a PNG
lScreenshot = getScreenAsImage()
lScreenshot.save('screenshot.png', format='png')
# lScreenshot = ScreenshotSecondScreen.grab_screen()
# save image file
# lScreenshot.save('screenshot.png')
# Сохранить файл на диск
SaveScreenshot("Screenshot.png")
lFileObject = open("Screenshot.png", "rb")
# Write content as utf-8 data
inRequest.OpenRPAResponseDict["Body"] = lFileObject.read()
# Закрыть файловый объект
lFileObject.close()
def SettingsUpdate(inGlobalConfiguration):
import os
import pyOpenRPA.Orchestrator
lOrchestratorFolder = "\\".join(pyOpenRPA.Orchestrator.__file__.split("\\")[:-1])
lURLList = \
[ #List of available URLs with the orchestrator server
#{
# "Method":"GET|POST",
# "URL": "/index", #URL of the request
# "MatchType": "", #"BeginWith|Contains|Equal|EqualCase",
# "ResponseFilePath": "", #Absolute or relative path
# "ResponseFolderPath": "", #Absolute or relative path
# "ResponseContentType": "", #HTTP Content-type
# "ResponseDefRequestGlobal": None #Function with str result
#}
#Orchestrator basic dependencies
{"Method":"POST", "URL": "/", "MatchType": "EqualCase", "ResponseDefRequestGlobal": SQLInsert, "ResponseContentType": "text/html"},
{"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"}
]
inGlobalConfiguration["Server"]["URLList"]=inGlobalConfiguration["Server"]["URLList"]+lURLList
return inGlobalConfiguration
\ No newline at end of file
r"""
The OpenRPA package (from UnicodeLabs)
"""
__all__ = []
__author__ = 'Ivan Maslov <ivan.maslov@unicodelabs.ru>'
\ No newline at end of file
import sys
lFolderPath = "\\".join(__file__.split("\\")[:-3])
sys.path.insert(0, lFolderPath)
from pyOpenRPA.Tools.RobotDB import RobotDB
\ No newline at end of file
def SettingsUpdate(inDict):
##################################################
#""/"ND" MethodMatchURLList
l__ND_RuleMethodMatchURLBeforeList={
("","ND"): {
"MethodMatchURLBeforeList": [
{
"Method":"GET",
"MatchType":"Beginwith",
"URL":"/",
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
"FlagAccess": True
},
{
"Method":"POST",
"MatchType":"Beginwith",
"URL":"/",
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
"FlagAccess": True
}
]
}
}
#Append to global list
inDict["Server"]["AccessUsers"]["RuleDomainUserDict"].update(l__ND_RuleMethodMatchURLBeforeList)
#Return current dict
return inDict
\ No newline at end of file
import datetime
def SettingsUpdate(inDict):
##################################################
#""/"SuperToken" MethodMatchURLList
l__SuperToken_RuleMethodMatchURLBeforeList={
("","SUPERTOKEN"): { #!!!!!only in upper case!!!!
"MethodMatchURLBeforeList": [
{
"Method":"GET",
"MatchType":"Beginwith",
"URL":"/",
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
"FlagAccess": True
},
{
"Method":"POST",
"MatchType":"Beginwith",
"URL":"/",
#"FlagAccessDefRequestGlobalAuthenticate": TestDef
"FlagAccess": True
}
]
}
}
#Append to global list
inDict["Server"]["AccessUsers"]["RuleDomainUserDict"].update(l__SuperToken_RuleMethodMatchURLBeforeList)
#"<AuthToken>":{"User":"", "Domain":"", "TokenDatetime":<Datetime>}
#!!!!!!!!!!!!!!!!!!!!!!!
#Attention: default supertoken is 1992-04-03-0643-ru-b4ff-openrpa52zzz - please change it when you will customize OpenRPA in your company
#!!!!!!!!!!!!!!!!!!!!!!!
inDict["Server"]["AccessUsers"]["AuthTokensDict"].update(
{"1992-04-03-0643-ru-b4ff-openrpa52zzz":{"User":"SuperToken", "Domain":"", "TokenDatetime": datetime.datetime.now(), "FlagDoNotExpire":True}}
)
#Return current dict
return inDict
\ No newline at end of file
import psutil
import datetime
import logging
import os
#RobotDB settings
def Settings():
import os
import pyOpenRPA.Orchestrator
lOrchestratorFolder = "\\".join(pyOpenRPA.Orchestrator.__file__.split("\\")[:-1])
mDict = {
"SQLite":{
"DBPath":os.path.join("\\".join(__file__.split("\\")[:-1]),"DB.db")
},
"Server": {
"ListenPort_": "Порт, по которому можно подключиться к демону",
"ListenPort": 81,
"ListenURLList": [
{
"Description": "Local machine test",
"URL_": "Сетевое расположение сервера демона",
"URL": "http://127.0.0.1:81"
}
],
"AccessUsers": { #Default - all URL is blocked
"FlagCredentialsAsk": True, #Turn on Authentication
"RuleDomainUserDict": {
#("DOMAIN", "USER"): { !!!!!only in upper case!!!!
# "MethodMatchURLBeforeList": [
# {
# "Method":"GET|POST",
# "MatchType":"BeginWith|Contains|Equal|EqualCase",
# "URL":"",
# "FlagAccessDefRequestGlobalAuthenticate": None, #Return bool
# "FlagAccess": True
# }
# ]
#}
},
"RuleMethodMatchURLBeforeList": [ #General MethodMatchURL list (no domain/user)
# {
# "Method":"GET|POST",
# "MatchType":"BeginWith|Contains|Equal|EqualCase",
# "URL":"",
# "FlagAccessDefRequestGlobalAuthenticate": None, #Return bool
# "FlagAccess": True
# }
],
"AuthTokensDict": {
#"<AuthToken>":{"User":"", "Domain":"", "TokenDatetime":<Datetime>, "FlagDoNotExpire":True}
}
},
"URLList":[ #List of available URLs with the orchestrator server
#{
# "Method":"GET|POST",
# "URL": "/index", #URL of the request
# "MatchType": "", #"BeginWith|Contains|Equal|EqualCase",
# "ResponseFilePath": "", #Absolute or relative path
# "ResponseFolderPath": "", #Absolute or relative path
# "ResponseContentType": "", #HTTP Content-type
# "ResponseDefRequestGlobal": None #Function with str result
#}
]
},
"Logger": logging.getLogger("RobotDB"),
"Storage": {} #Orchestrator storage - not used
}
#Создать файл логирования
# add filemode="w" to overwrite
if not os.path.exists("Reports"):
os.makedirs("Reports")
##########################
#Подготовка логгера Robot
#########################
mRobotLogger=mDict["Logger"]
mRobotLogger.setLevel(logging.INFO)
# create the logging file handler
mRobotLoggerFH = logging.FileHandler("Reports\ReportRobotDB_"+datetime.datetime.now().strftime("%Y_%m_%d")+".log")
mRobotLoggerFormatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
mRobotLoggerFH.setFormatter(mRobotLoggerFormatter)
# add handler to logger object
mRobotLogger.addHandler(mRobotLoggerFH)
############################################
###################################
#Init .py files from Settings folder
####################################
#Get file list from Settings folder
import os
import pdb
#lFunction to call in subfiles
lSubmoduleFunctionName = "SettingsUpdate"
#lSettingsPath = os.path.join(inSettingsFolderPath, "Settings")
lSettingsPath = "\\".join(__file__.split("\\")[:-1])
#lSettingsPath = os.path.join(os.getcwd(), "Settings")
#Lambda function to get files .py from settings folder except Settings.py
lFileList = [f for f in os.listdir(lSettingsPath) if os.path.isfile(os.path.join(lSettingsPath, f)) and f.split(".")[-1] == "py" and os.path.join(lSettingsPath, f) != __file__]
import importlib.util
for lModuleFilePathItem in lFileList:
lModuleName = lModuleFilePathItem[0:-3]
lFileFullPath = os.path.join(lSettingsPath, lModuleFilePathItem)
lTechSpecification = importlib.util.spec_from_file_location(lModuleName, lFileFullPath)
lTechModuleFromSpec = importlib.util.module_from_spec(lTechSpecification)
lTechSpecificationModuleLoader = lTechSpecification.loader.exec_module(lTechModuleFromSpec)
if lSubmoduleFunctionName in dir(lTechModuleFromSpec):
#Run SettingUpdate function in submodule
getattr(lTechModuleFromSpec, lSubmoduleFunctionName)(mDict)
return mDict
\ No newline at end of file
cd %~dp0..\..\Sources
copy /Y ..\Resources\WPy64-3720\python-3.7.2.amd64\python.exe ..\Resources\WPy64-3720\python-3.7.2.amd64\OpenRPA_RobotDB.exe
..\Resources\WPy64-3720\python-3.7.2.amd64\OpenRPA_RobotDB.exe -m pyOpenRPA.Tools.RobotDB "..\Utils\RobotDB\SettingsExample.py"
pause >nul
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment