Commit 6af255f66134824a339740a387dc9c7e237b9b22
1 parent
6bcd9989
Exists in
master
update code to py 3
Showing
19 changed files
with
307 additions
and
395 deletions
Show diff stats
development.ini
1 | 1 | [WSCBot] |
2 | -###Url de acesso ao modulo wscserver (terminar com '/') | |
3 | -url_wscserver: http://localhost/wscserver/ | |
4 | 2 | |
5 | -###Url de acesso ao Super Gerente | |
6 | -ip_superg: http://localhost/lbbulk/reg | |
3 | +# Url de acesso ao modulo wscserver | |
4 | +url_wscserver: http://127.0.0.1/rest/coleta | |
7 | 5 | |
8 | -###Local do disco onde o arquivo será salvo temporariamente | |
6 | +# Url de acesso ao módulo LBBulk | |
7 | +url_lbbulk: http://127.0.0.1/lbbulk/reg | |
8 | + | |
9 | +#Local do disco onde o arquivo será salvo temporariamente | |
9 | 10 | filepath: /tmp/extract/ |
10 | 11 | |
11 | -###Nome da fonte dos dados (precisa ser um nome já existente na base do super-gerente) | |
12 | +# Nome da fonte dos dados | |
13 | +# (precisa ser um nome já existente na base do super-gerente) | |
12 | 14 | source_name: brlight |
13 | 15 | |
14 | -###Local temporario para download de arquivos, comente para usar o diretorio temporario padrão do sistema | |
15 | -tmp_dir: /home/tmp | |
16 | - | |
17 | -###Nome de usuário | |
18 | -username: rest | |
19 | - | |
20 | -###senha do usuário | |
21 | -senha: rest | |
22 | - | |
23 | -###data da coleta | |
24 | -data: 01-01-1970 | |
25 | - | |
26 | -###Tempo entre as leituras em busca de registros (em segundos) | |
27 | -sleep_time: 60 | |
16 | +# Tempo entre as leituras em busca de registros (em segundos) | |
17 | +sleep_time: 2 | |
28 | 18 | |
29 | 19 | [Daemon] |
30 | -stdin_path = /dev/null | |
31 | -stdout_path = /dev/tty | |
32 | -stderr_path = /dev/tty | |
20 | + | |
33 | 21 | pidfile_path = /var/run/wscbot.pid |
34 | 22 | logfile_path = /var/log/wscbot.log |
35 | -pidfile_timeout = 5 | ... | ... |
production.ini
1 | 1 | [WSCBot] |
2 | -###Url de acesso ao modulo wscserver (terminar com '/') | |
3 | -url_wscserver: http://localhost/wscserver/ | |
4 | 2 | |
5 | -###Url de acesso ao Super Gerente | |
6 | -ip_superg: http://localhost/lbbulk/reg | |
3 | +# Url de acesso ao modulo wscserver | |
4 | +url_wscserver: http://127.0.0.1/rest/coleta | |
7 | 5 | |
8 | -###Local do disco onde o arquivo será salvo temporariamente | |
9 | -filepath: /home/extract | |
6 | +# Url de acesso ao módulo LBBulk | |
7 | +url_lbbulk: http://127.0.0.1/lbbulk/reg | |
10 | 8 | |
11 | -###Nome da fonte dos dados (precisa ser um nome já existente na base do super-gerente) | |
12 | -source_name: cacic_mpog | |
9 | +#Local do disco onde o arquivo será salvo temporariamente | |
10 | +filepath: /tmp/extract/ | |
13 | 11 | |
14 | -###Local temporario para download de arquivos, comente para usar o diretorio temporario padrão do sistema | |
15 | -tmp_dir: /home/tmp | |
12 | +# Nome da fonte dos dados | |
13 | +# (precisa ser um nome já existente na base do super-gerente) | |
14 | +source_name: brlight | |
16 | 15 | |
17 | -###Nome de usuário | |
18 | -username: rest | |
19 | - | |
20 | -###senha do usuário | |
21 | -senha: rest | |
22 | - | |
23 | -###data da coleta | |
24 | -data: 01-01-1970 | |
25 | - | |
26 | -###Tempo entre as leituras em busca de registros (em segundos) | |
27 | -sleep_time: 86400 | |
16 | +# Tempo entre as leituras em busca de registros (em segundos) | |
17 | +sleep_time: 2 | |
28 | 18 | |
29 | 19 | [Daemon] |
30 | -stdin_path = /dev/null | |
31 | -stdout_path = /dev/tty | |
32 | -stderr_path = /dev/tty | |
20 | + | |
33 | 21 | pidfile_path = /var/run/wscbot.pid |
34 | 22 | logfile_path = /var/log/wscbot.log |
35 | -pidfile_timeout = 5 | ... | ... |
setup.py
1 | 1 | from setuptools import setup, find_packages |
2 | 2 | |
3 | - | |
4 | 3 | requires = [ |
5 | 4 | 'ConfigParser', |
6 | 5 | 'requests', |
7 | - 'lockfile', | |
8 | - 'python-daemon', | |
9 | - 'simplejson' | |
10 | 6 | ] |
11 | 7 | |
12 | 8 | setup( |
... | ... | @@ -15,7 +11,7 @@ setup( |
15 | 11 | author = "Lightbase", |
16 | 12 | author_email = "breno.brito@lightbase.com.br", |
17 | 13 | url = "https://pypi.python.org/pypi/LBConverter", |
18 | - description = "Daemon Converter for the neo-lightbase service", | |
14 | + description = "Daemon for the neo-lightbase service", | |
19 | 15 | license = "GPLv2", |
20 | 16 | keywords = "Converter extractor lightbase daemon", |
21 | 17 | install_requires=requires, | ... | ... |
wscbot/__main__.py
1 | 1 | #!/usr/bin/python |
2 | 2 | # -*- coding: utf-8 -*- |
3 | -import logging | |
4 | -import time | |
5 | -import os | |
6 | -import ConfigParser | |
7 | - | |
8 | -from daemon import runner | |
9 | 3 | |
10 | - | |
11 | -from app import main | |
12 | - | |
13 | -#exceptions | |
14 | -from requests.exceptions import * | |
4 | +import sys | |
5 | +import time | |
6 | +import logging | |
15 | 7 | import zipfile |
16 | -import lockfile | |
17 | -import tempfile | |
18 | - | |
19 | -# absolute path to .ini file | |
20 | -#ini_path='/srv/super-gerente/WSCBot/development.ini' | |
21 | -ini_path='/srv/bot-super-gerente/WSCBot/production.ini' | |
22 | - | |
23 | - | |
24 | - | |
25 | -def setconfig(config_file): | |
26 | - """Função que conecta o modulo ao arquivo de configurações""" | |
8 | +import traceback | |
9 | +from wscbot import robot | |
10 | +from wscbot import config | |
11 | +from wscbot.daemon import Daemon | |
12 | +from requests.exceptions import * | |
27 | 13 | |
28 | - config_file = os.path.abspath(config_file) | |
29 | - config = ConfigParser.ConfigParser() | |
30 | - config.read(config_file) | |
31 | - user = {} | |
32 | - user['url_wscserver'] = config.get('WSCBot', 'url_wscserver') | |
33 | - user['filepath'] = config.get('WSCBot', 'filepath') | |
34 | - if config.has_option('WSCBot', 'tmp_dir'): | |
35 | - user['tmp_dir'] = config.get('WSCBot', 'tmp_dir') | |
36 | - else: | |
37 | - user['tmp_dir'] = tempfile.mkdtemp() | |
38 | - user['username'] = config.get('WSCBot', 'username') | |
39 | - user['senha'] = config.get('WSCBot', 'senha') | |
40 | - user['data'] = config.get('WSCBot', 'data') | |
41 | - user['ip_superg'] = config.get('WSCBot', 'ip_superg') | |
42 | - user['source_name'] = config.get('WSCBot', 'source_name') | |
43 | - user['sleep_time'] = int(config.get('WSCBot', 'sleep_time')) | |
44 | - user['stdin_path'] = config.get('Daemon', 'stdin_path') | |
45 | - user['stdout_path'] = config.get('Daemon', 'stdout_path') | |
46 | - user['stderr_path'] = config.get('Daemon', 'stderr_path') | |
47 | - user['pidfile_path'] = config.get('Daemon', 'pidfile_path') | |
48 | - user['logfile_path'] = config.get('Daemon', 'logfile_path') | |
49 | - user['pidfile_timeout'] = int(config.get('Daemon', 'pidfile_timeout')) | |
50 | - return user | |
14 | +config.setup_config() | |
51 | 15 | |
52 | -class App(): | |
16 | +# Set up log configurations | |
17 | +logger = logging.getLogger("WSCBot") | |
18 | +logger.setLevel(logging.DEBUG) | |
19 | +format_pattern = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' | |
20 | +formatter = logging.Formatter(format_pattern) | |
21 | +handler = logging.FileHandler(config.LOGFILE_PATH) | |
22 | +handler.setFormatter(formatter) | |
23 | +logger.addHandler(handler) | |
53 | 24 | |
54 | - def __init__(self): | |
55 | - self.stdin_path = user['stdin_path'] | |
56 | - self.stdout_path = user['stdout_path'] | |
57 | - self.stderr_path = user['stderr_path'] | |
58 | - self.pidfile_path = user['pidfile_path'] | |
59 | - self.pidfile_timeout = user['pidfile_timeout'] | |
25 | +class WSCBot(Daemon): | |
60 | 26 | |
61 | 27 | def run(self): |
62 | 28 | logger.info ('Iniciando modulo WSCBot') |
63 | 29 | while True: |
64 | - timeron = time.time() | |
65 | 30 | logger.info ('Iniciando execução') |
66 | 31 | try: |
67 | - main(ip_servidor,username,senha,ip_superg,filepath,data,tmp_dir,source_name) | |
32 | + robot.main() | |
68 | 33 | except (ConnectionError, Timeout): |
69 | - logger.error ('Não foi possivel estabelecer conexão com o servidor! ' + domain) | |
70 | - except zipfile.BadZipfile: | |
71 | - logger.error ('Arquivo zip gerado pelo WSCServer invalido ou corrompido') | |
34 | + logger.error('Não foi possivel estabelecer conexão com o servidor! ' + domain) | |
72 | 35 | except Exception as erro: |
73 | - logger.error (erro) | |
74 | - timeronff = time.time() | |
75 | - tempo = (timeronff - timeron) | |
76 | - m, s = divmod(sleep_time, 60) | |
77 | - h, m = divmod(m, 60) | |
78 | - next = "%d:%02d:%02d" % (h, m, s) | |
79 | - logger.debug ('Execução durou ' + str(tempo) + ' segundos.') | |
80 | - logger.info ('Proxima execução em: ' + next) | |
81 | - time.sleep(sleep_time) | |
82 | - | |
83 | -user = setconfig(ini_path) | |
84 | -ip_servidor = user['url_wscserver'] | |
85 | -senha = user['senha'] | |
86 | -ip_superg = user['ip_superg'] | |
87 | -sleep_time = user['sleep_time'] | |
88 | -source_name = user['source_name'] | |
89 | -username = user['username'] | |
90 | -filepath = user['filepath'] | |
91 | -tmp_dir = user['tmp_dir'] | |
92 | -data = user['data'] | |
93 | -app = App() | |
94 | -logger = logging.getLogger("WSCBot") | |
95 | -logger.setLevel(logging.INFO) # Alterar para logging.INFO em produção | |
96 | -formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') | |
97 | -handler = logging.FileHandler(user['logfile_path']) | |
98 | -handler.setFormatter(formatter) | |
99 | -logger.addHandler(handler) | |
36 | + logger.critical(traceback.format_exc()) | |
37 | + time.sleep(config.SLEEP_TIME) | |
38 | + | |
39 | + | |
40 | +if __name__ == "__main__": | |
41 | + | |
42 | + daemon = WSCBot(config.PIDFILE_PATH) | |
43 | + | |
44 | + if len(sys.argv) == 2: | |
45 | + if 'start' == sys.argv[1]: | |
46 | + print('starting daemon ...') | |
47 | + daemon.start() | |
48 | + elif 'stop' == sys.argv[1]: | |
49 | + print('stopping daemon ...') | |
50 | + daemon.stop() | |
51 | + elif 'restart' == sys.argv[1]: | |
52 | + print('restarting daemon ...') | |
53 | + daemon.restart() | |
54 | + else: | |
55 | + print("Unknown command") | |
56 | + sys.exit(2) | |
57 | + sys.exit(0) | |
58 | + else: | |
59 | + print("usage: %s start|stop|restart" % sys.argv[0]) | |
60 | + sys.exit(2) | |
100 | 61 | |
101 | -daemon_runner = runner.DaemonRunner(app) | |
102 | -#This ensures that the logger file handle does not get closed during daemonization | |
103 | -daemon_runner.daemon_context.files_preserve=[handler.stream] | |
104 | -try: | |
105 | - daemon_runner.do_action() | |
106 | -except (KeyboardInterrupt, SystemExit): | |
107 | - raise | |
108 | -except lockfile.LockTimeout: | |
109 | - print("\nErro: Já existe uma instância desse modulo em execução\n") | |
110 | -except runner.DaemonRunnerStopFailureError: | |
111 | - print("\nErro: Não existe nenhuma instância desse módulo em execução\n") | ... | ... |
wscbot/app.py
... | ... | @@ -1,40 +0,0 @@ |
1 | - # -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | -import json | |
4 | - | |
5 | -from requests import put, post | |
6 | -import logging | |
7 | - | |
8 | -from wscbot.scripts import req | |
9 | -from wscbot.scripts import pegachave | |
10 | -from wscbot.scripts import erro | |
11 | -from wscbot.scripts import rotinas | |
12 | -from wscbot.scripts.zipparser import ziphandler | |
13 | - | |
14 | - | |
15 | - | |
16 | -def main(ip_servidor,username,senha,ip_superg,filepath,data,tmp_dir, | |
17 | - source_name): | |
18 | - """ | |
19 | - Envia uma requisição GET HTTP para o endereço cadastrado fornecendo | |
20 | - como parâmetros da requisição o usuário e senha informados, pega a | |
21 | - resposta da requisição e escreve num arquivo. Criptografa o conteúdo | |
22 | - do arquivo com base em uma chave compartilhada com o Super Gerente. | |
23 | - Envia o arquivo criptografado para o Super Gerente e registra a data | |
24 | - do envio e o resultado da comunicação. | |
25 | - """ | |
26 | - | |
27 | - # Faz a requisição do arquivo zip | |
28 | - zip_path = req.req(ip_servidor, filepath) | |
29 | - | |
30 | - dicionario = ziphandler(zip_path, tmp_dir) | |
31 | - for arquivo in dicionario: | |
32 | - logger.debug('Inicio do envio de dados') | |
33 | - coleta = json.loads(dicionario[arquivo])['results'] | |
34 | - for registro in coleta: | |
35 | - registro['name_source'] = source_name | |
36 | - registro = json.dumps(registro) | |
37 | - f = post(ip_superg,data={'json_reg':registro}) | |
38 | - erro.is_error_p(f) | |
39 | - | |
40 | -logger = logging.getLogger("WSCBot") |
... | ... | @@ -0,0 +1,30 @@ |
1 | + | |
2 | +import tempfile | |
3 | +import configparser | |
4 | + | |
5 | +def setup_config(): | |
6 | + | |
7 | + global INI_FILE | |
8 | + | |
9 | + INI_FILE = 'development.ini' | |
10 | + | |
11 | + config = configparser.ConfigParser() | |
12 | + config.read(INI_FILE) | |
13 | + | |
14 | + global URL_WSCSERVER | |
15 | + global URL_LBBULK | |
16 | + | |
17 | + URL_WSCSERVER = config.get('WSCBot', 'url_wscserver') | |
18 | + URL_LBBULK = config.get('WSCBot', 'url_lbbulk') | |
19 | + | |
20 | + global FILEPATH | |
21 | + global SOURCE_NAME | |
22 | + global SLEEP_TIME | |
23 | + global PIDFILE_PATH | |
24 | + global LOGFILE_PATH | |
25 | + | |
26 | + FILEPATH = config.get('WSCBot', 'filepath') | |
27 | + SOURCE_NAME = config.get('WSCBot', 'source_name') | |
28 | + SLEEP_TIME = int(config.get('WSCBot', 'sleep_time')) | |
29 | + PIDFILE_PATH = config.get('Daemon', 'pidfile_path') | |
30 | + LOGFILE_PATH = config.get('Daemon', 'logfile_path') | ... | ... |
... | ... | @@ -0,0 +1,132 @@ |
1 | + | |
2 | +""" | |
3 | +Generic linux daemon base class for python 3.x. | |
4 | +Original Author: | |
5 | +http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/ | |
6 | +""" | |
7 | + | |
8 | +import sys, os, time, atexit, signal | |
9 | + | |
10 | +class Daemon: | |
11 | + | |
12 | + """ A generic daemon class. | |
13 | + Usage: subclass the daemon class and override the run() method. | |
14 | + """ | |
15 | + | |
16 | + def __init__(self, pidfile): | |
17 | + self.pidfile = pidfile | |
18 | + | |
19 | + def daemonize(self): | |
20 | + """Deamonize class. UNIX double fork mechanism.""" | |
21 | + | |
22 | + try: | |
23 | + pid = os.fork() | |
24 | + if pid > 0: | |
25 | + # exit first parent | |
26 | + sys.exit(0) | |
27 | + except OSError as err: | |
28 | + sys.stderr.write('fork #1 failed: {0}\n'.format(err)) | |
29 | + sys.exit(1) | |
30 | + | |
31 | + # decouple from parent environment | |
32 | + os.chdir('/') | |
33 | + os.setsid() | |
34 | + os.umask(0) | |
35 | + | |
36 | + # do second fork | |
37 | + try: | |
38 | + pid = os.fork() | |
39 | + if pid > 0: | |
40 | + | |
41 | + # exit from second parent | |
42 | + sys.exit(0) | |
43 | + except OSError as err: | |
44 | + sys.stderr.write('fork #2 failed: {0}\n'.format(err)) | |
45 | + sys.exit(1) | |
46 | + | |
47 | + # redirect standard file descriptors | |
48 | + os.setsid() | |
49 | + | |
50 | + sys.stdin.flush() | |
51 | + sys.stdout.flush() | |
52 | + sys.stderr.flush() | |
53 | + | |
54 | + null = os.open(os.devnull, os.O_RDWR) | |
55 | + | |
56 | + os.dup2(null, sys.stdin.fileno()) | |
57 | + os.dup2(null, sys.stdout.fileno()) | |
58 | + os.dup2(null, sys.stderr.fileno()) | |
59 | + | |
60 | + os.close(null) | |
61 | + | |
62 | + # write pidfile | |
63 | + atexit.register(self.delpid) | |
64 | + | |
65 | + pid = str(os.getpid()) | |
66 | + with open(self.pidfile,'w+') as f: | |
67 | + f.write(pid + '\n') | |
68 | + | |
69 | + def delpid(self): | |
70 | + os.remove(self.pidfile) | |
71 | + | |
72 | + def start(self): | |
73 | + """ Start the daemon.""" | |
74 | + | |
75 | + # Check for a pidfile to see if the daemon already runs | |
76 | + try: | |
77 | + with open(self.pidfile,'r') as pf: | |
78 | + pid = int(pf.read().strip()) | |
79 | + except IOError: | |
80 | + pid = None | |
81 | + | |
82 | + if pid: | |
83 | + message = "pidfile {0} already exist. " + \ | |
84 | + "Daemon already running?\n" | |
85 | + sys.stderr.write(message.format(self.pidfile)) | |
86 | + sys.exit(1) | |
87 | + | |
88 | + # Start the daemon | |
89 | + self.daemonize() | |
90 | + self.run() | |
91 | + | |
92 | + def stop(self): | |
93 | + """Stop the daemon.""" | |
94 | + | |
95 | + # Get the pid from the pidfile | |
96 | + try: | |
97 | + with open(self.pidfile,'r') as pf: | |
98 | + pid = int(pf.read().strip()) | |
99 | + except IOError: | |
100 | + pid = None | |
101 | + | |
102 | + if not pid: | |
103 | + message = "pidfile {0} does not exist. " + \ | |
104 | + "Daemon not running?\n" | |
105 | + sys.stderr.write(message.format(self.pidfile)) | |
106 | + return # not an error in a restart | |
107 | + | |
108 | + # Try killing the daemon process | |
109 | + try: | |
110 | + while 1: | |
111 | + os.kill(pid, signal.SIGTERM) | |
112 | + time.sleep(0.1) | |
113 | + except OSError as err: | |
114 | + e = str(err.args) | |
115 | + if e.find("No such process") > 0: | |
116 | + if os.path.exists(self.pidfile): | |
117 | + os.remove(self.pidfile) | |
118 | + else: | |
119 | + print (str(err.args)) | |
120 | + sys.exit(1) | |
121 | + | |
122 | + def restart(self): | |
123 | + """Restart the daemon.""" | |
124 | + self.stop() | |
125 | + self.start() | |
126 | + | |
127 | + def run(self): | |
128 | + """You should override this method when you subclass Daemon. | |
129 | + | |
130 | + It will be called after the process has been daemonized by | |
131 | + start() or restart().""" | |
132 | + | ... | ... |
wscbot/doc/classes_wscbot.png
4.41 KB
wscbot/doc/packages_wscbot.png
31.6 KB
wscbot/model/__init__.py
... | ... | @@ -0,0 +1,76 @@ |
1 | + | |
2 | +# -*- coding: utf-8 -*- | |
3 | + | |
4 | +import os | |
5 | +import uuid | |
6 | +import logging | |
7 | +import zipfile | |
8 | +import requests | |
9 | +from wscbot import config | |
10 | + | |
11 | +def main(): | |
12 | + | |
13 | + """ | |
14 | + Envia uma requisição GET HTTP para o endereço cadastrado fornecendo | |
15 | + como parâmetros da requisição o usuário e senha informados, pega a | |
16 | + resposta da requisição e escreve num arquivo. Criptografa o conteúdo | |
17 | + do arquivo com base em uma chave compartilhada com o Super Gerente. | |
18 | + Envia o arquivo criptografado para o Super Gerente e registra a data | |
19 | + do envio e o resultado da comunicação. | |
20 | + """ | |
21 | + | |
22 | + params = { | |
23 | + #'zip' : '0', # Will return JSON | |
24 | + 'zip' : '1', # Will return zip | |
25 | + 'limit' : '100'} | |
26 | + | |
27 | + logger.debug('Baixando arquivo zip ...') | |
28 | + zip_path = download_file(config.URL_WSCSERVER, params) | |
29 | + | |
30 | + if zip_path is not None: | |
31 | + zip_path = os.path.abspath(zip_path) | |
32 | + logger.debug('Enviando arquivo zip ...') | |
33 | + upload_file(config.URL_LBBULK, zip_path, config.SOURCE_NAME) | |
34 | + os.remove(zip_path) | |
35 | + | |
36 | +def download_file(url, params): | |
37 | + """ | |
38 | + Download file from url | |
39 | + """ | |
40 | + fname = str(uuid.uuid4()) + '.zip' | |
41 | + local_filename = config.FILEPATH + '/' + fname | |
42 | + req = requests.get(url, stream=True, params=params) | |
43 | + try: | |
44 | + req.raise_for_status() | |
45 | + except: | |
46 | + logger.error(""" | |
47 | + Erro ao tentar baixar arquivo na url %s. Resposta: %s | |
48 | + """ % (url, req._content)) | |
49 | + return None | |
50 | + | |
51 | + if not os.path.exists(config.FILEPATH): | |
52 | + os.makedirs(config.FILEPATH) | |
53 | + | |
54 | + with open(local_filename, 'wb') as f: | |
55 | + for chunk in req.iter_content(chunk_size=1024): | |
56 | + if chunk: # filter out keep-alive new chunks | |
57 | + f.write(chunk) | |
58 | + f.flush() | |
59 | + | |
60 | + return local_filename | |
61 | + | |
62 | +def upload_file(url, file_path, source_name): | |
63 | + | |
64 | + params = {'source_name': source_name} | |
65 | + files = {'file': open(file_path, 'rb')} | |
66 | + req = requests.post(url, params=params, files=files) | |
67 | + | |
68 | + try: | |
69 | + req.raise_for_status() | |
70 | + except: | |
71 | + logger.error(""" | |
72 | + Erro ao tentar enviar arquivo na url %s. Resposta: %s | |
73 | + """ % (url, req._content)) | |
74 | + return None | |
75 | + | |
76 | +logger = logging.getLogger("WSCBot") | ... | ... |
wscbot/scripts/__init__.py
wscbot/scripts/erro.py
... | ... | @@ -1,38 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | -import logging | |
4 | -import simplejson # for exception | |
5 | - | |
6 | -def is_error_p(resp): | |
7 | - """verifica erros do post""" | |
8 | - try: | |
9 | - json = resp.json() | |
10 | - except simplejson.decoder.JSONDecodeError: | |
11 | - msg = 'not found' | |
12 | - n_err = str(resp.status_code) | |
13 | - logger.error(n_err + ': ' + msg) | |
14 | - else: | |
15 | - try: | |
16 | - a = len(json) | |
17 | - except TypeError: | |
18 | - id_reg = str(json) | |
19 | - logger.info('Escrito com sucesso id_reg: ' + id_reg) | |
20 | - else: | |
21 | - msg = json['_error_message'] | |
22 | - n_err = str(json['_status']) | |
23 | - logger.error(n_err + ': ' + msg) | |
24 | - | |
25 | - | |
26 | -def is_error_g(recebe): | |
27 | - """Verifica erros do GET""" | |
28 | - | |
29 | - num_er = recebe.__dict__['status_code'] | |
30 | - msg = recebe.__dict__['reason'] | |
31 | - | |
32 | - if num_er > 199 and num_er < 300: | |
33 | - logger.debug('Recebido com sucesso.') | |
34 | - else: | |
35 | - logger.error(str(num_err) + ': ' + msg) | |
36 | - | |
37 | - | |
38 | -logger = logging.getLogger("WSCBot") | |
39 | 0 | \ No newline at end of file |
wscbot/scripts/pegachave.py
... | ... | @@ -1,19 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | -from requests import get | |
4 | - | |
5 | -def pegachave(domain,username,senha): | |
6 | - """Envia uma requisição GET HTTP para o endereço cadastrado, | |
7 | - fornecendo como parâmetros da requisição o usuário e senha informados;""" | |
8 | - | |
9 | - payload = {'user' : 'username', | |
10 | - 'pass' : 'senha'} | |
11 | - | |
12 | - recebe = get(domain, data=payload) | |
13 | - # jsonfull = recebe.json() | |
14 | - # bases = jsonfull["results"] | |
15 | - chave = t_dados(recebe) | |
16 | - | |
17 | - | |
18 | - return chave | |
19 | - |
wscbot/scripts/req.py
... | ... | @@ -1,48 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | -# from requests import get | |
4 | -import urllib | |
5 | -import logging | |
6 | -import os | |
7 | - | |
8 | -from wscbot.scripts.erro import is_error_g | |
9 | -from wscbot.scripts.tratamento import t_dados | |
10 | - | |
11 | - | |
12 | -def download_file(url, filepath): | |
13 | - """Baixa o arquivo de coleta na url indicada""" | |
14 | - | |
15 | - if not os.path.isdir(filepath): | |
16 | - os.mkdir(filepath) | |
17 | - local_filename = filepath + "coleta.zip" | |
18 | - urllib.urlretrieve(url, local_filename) | |
19 | - return local_filename | |
20 | - | |
21 | - | |
22 | -def req(domain,filepath): #Recebia domain e data | |
23 | - """Envia uma requisição GET HTTP para o endereço cadastrado, | |
24 | - fornecendo como parâmetros da requisição o usuário e senha informados;""" | |
25 | - | |
26 | - # payload = {'user' : 'username', | |
27 | - # 'pass' : 'senha'} | |
28 | - logger.debug('Mandando requisição') | |
29 | - url = domain + 'zip/coleta' | |
30 | - | |
31 | - # values = {'data_coleta':data} | |
32 | - | |
33 | - arquivo_coleta = download_file(url,filepath) # , param=values | |
34 | - arquivo_coleta = os.path.abspath(arquivo_coleta) | |
35 | - | |
36 | - # ATENCAO!!! | |
37 | - # tem de se testar se o data precisa de encoding!! | |
38 | - | |
39 | - # funcionava para o módulo requests | |
40 | - # Não sei como fazer para o urllib | |
41 | - # is_error_g(arquivo_coleta) | |
42 | - | |
43 | - return arquivo_coleta | |
44 | - | |
45 | -logger = logging.getLogger("WSCBot") | |
46 | - | |
47 | -# zip para baixar e testar: | |
48 | -# http://10.0.0.149/api/doc/arquivos/29/download | |
49 | 0 | \ No newline at end of file |
wscbot/scripts/rotinas.py
... | ... | @@ -1,27 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | -import logging | |
4 | - | |
5 | -def so(): | |
6 | - """SO""" | |
7 | - logger.debug('Iniciando a rotina SO') | |
8 | - pass | |
9 | - | |
10 | -def software(): | |
11 | - """software""" | |
12 | - logger.debug('Iniciando a rotina software') | |
13 | - pass | |
14 | - | |
15 | -def hardware(): | |
16 | - """hardware""" | |
17 | - logger.debug('Iniciando a rotina hardware') | |
18 | - pass | |
19 | - | |
20 | -def software_basico(): | |
21 | - """software_basico""" | |
22 | - logger.debug('Iniciando a rotina software_basico') | |
23 | - pass | |
24 | - | |
25 | - | |
26 | - | |
27 | -logger = logging.getLogger("WSCBot") | |
28 | 0 | \ No newline at end of file |
wscbot/scripts/tratamento.py
wscbot/scripts/xmlparser.py
... | ... | @@ -1,19 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | - | |
3 | -""" | |
4 | -Faz o parse do arquivo XML | |
5 | - | |
6 | -""" | |
7 | -"""Autor: Breno Rodrigues Brito""" | |
8 | -import xml.etree.ElementTree as ET | |
9 | -# from xml.dom import minidom | |
10 | - | |
11 | -tree = ET.parse(pathtofile) | |
12 | -root = tree.getroot() | |
13 | - | |
14 | -# xmldoc = minidom.parse('items.xml') | |
15 | -# itemlist = xmldoc.getElementsByTagName('item') | |
16 | -# print len(itemlist) | |
17 | -# print itemlist[0].attributes['name'].value | |
18 | -# for s in itemlist : | |
19 | -# print s.attributes['name'].value |
wscbot/scripts/zipparser.py
... | ... | @@ -1,49 +0,0 @@ |
1 | -# -*- coding: utf-8 -*- | |
2 | -"""Autor: Breno Rodrigues Brito""" | |
3 | - | |
4 | -import zipfile | |
5 | -import logging | |
6 | -import json | |
7 | -import os | |
8 | - | |
9 | -from wscbot.scripts.tratamento import t_dados | |
10 | - | |
11 | -def ziphandler(filename, tmp_dir): | |
12 | - """ | |
13 | - Receive a zip file and parse one file at a time, returning a collection of parsed files. | |
14 | - """ | |
15 | - # Create the zipfile object | |
16 | - z_root = zipfile.ZipFile(filename) | |
17 | - | |
18 | - # Create a temp dir and unzip file contents | |
19 | - | |
20 | - # registros = { | |
21 | - # 'import_error' : [], | |
22 | - # 'registros' : [] | |
23 | - # } | |
24 | - | |
25 | - | |
26 | - # cria um dicionario | |
27 | - for arquivo in z_root.namelist(): | |
28 | - # This should be a list with a all the zip files | |
29 | - #print('00000000000000000000000000000 %s' % arquivo) | |
30 | - z_root.extract(arquivo,tmp_dir) | |
31 | - | |
32 | - # This is the file object for this registro | |
33 | - # z = zipfile.ZipFile(os.path.join(tmp_dir,arquivo)) | |
34 | - filepath = (os.path.join(tmp_dir,arquivo)) | |
35 | - | |
36 | - # Lê o arquivo string que vai conter o json | |
37 | - with open(filepath) as f: | |
38 | - string_json = f.read() | |
39 | - | |
40 | - # carrega o Json | |
41 | - jsonfull = json.loads(string_json) | |
42 | - jsonfull = t_dados(jsonfull) | |
43 | - # cria um dicionario | |
44 | - dicionario = {arquivo:jsonfull} | |
45 | - | |
46 | - return dicionario | |
47 | - # lista de arquivos | |
48 | - | |
49 | -logger = logging.getLogger("WSCBot") |