Ejemplo n.º 1
0
def test_get_config():
	"""
	Tes konfigurasi dari
		meta > tutorial > cabang
	"""
	# file ga ada
	nodata = get_config("ga-ada.yaml")
	assert nodata == None

	data = get_config()
	assert data['title'] == "Haluang"
	assert data['desc']
	# ga usah pakai domain website, PENTING
	assert data['baseurl'] == "/"
	for tutor in data:
		if tutor in ["title", "desc", "baseurl"]:
			continue
		tutorial = data[tutor]
		assert tutorial['title'] # punya judul
		assert tutorial['desc'] # punya deskripsi
		assert tutorial['icon'] # punya ikon (dari font-awesome)
		if not tutorial['rilis']: # abaikan non rilis
			continue
		subdata = get_config("{}.yaml".format(tutor))
		for cabang in subdata:
			assert cabang['title']
			assert cabang['desc']
			if not cabang['rilis']:
				continue
			assert tutor in cabang['url']
			assert cabang['url'] != "#"
Ejemplo n.º 2
0
def get_konf_tutorial(tut):
    konf = {}
    data = app.get_config()
    for d in data:
        if d == tut:
            konf['meta'] = data[d]
            break
    data = app.get_config("{}.yaml".format(tut))
    konf['tutorial'] = data
    return konf
Ejemplo n.º 3
0
def test_index(client):
	"""
	Tes route "/"
	Hanya tutorial yang rilis ditampilkan
	"""
	req = client.get('/')
	req_data = str(req.data)
	site_config = get_config()
	soup = Soup(req.data, 'html.parser')
	for conf in daftar_tutorial():
		if not site_config[conf]['rilis']:
			judul = soup.find("div", attrs={"id":"tutorial-{}".format(conf)})
			assert judul == None
			continue

		# Data-data yang harus ada
		## Judul tutorial
		judul = soup.find("div", attrs={"id":"tutorial-{}".format(conf)})
		assert site_config[conf]['title'] in judul.text.strip()
		## Ikon
		ikon = judul.find("i")
		assert site_config[conf]['icon'] in ikon['class']

		# Data cabang-cabang tutorial
		tutorial_config = get_config("{}.yaml".format(conf))
		for item in tutorial_config[:3]:
			nama_class = "cabang-tutorial-{}".format(item['title'])
			cabang = soup.find('div',attrs={'id': nama_class})
			if item['rilis']:
				btn = cabang.find("a", attrs={'class': 'button'})
				# button class bukan `border--muted`
				assert "border--muted" not in btn['class']
				# teks button: "Buka"
				assert "Buka" in btn.text
				# url: / tutorial / cabang /
				assert item['url'] == btn['href'].strip()
			else:
				btn = cabang.find("a", attrs={'class': 'button'})
				# button class `border--muted`
				assert "border--muted" in btn['class']
				# teks button: "Segera"
				assert "Segera" in btn.text
				# url: #
				assert btn['href'].strip() == "#"
		
		# Selengkapnya
		nama_id = 'daftar-tutorial-' + conf
		print(nama_id)
		div = soup.find("div", attrs={'id': nama_id})
		tutorial_link = div.find("a")
		assert tutorial_link['href'].strip() == "/{}/".format(conf)
Ejemplo n.º 4
0
def test_tutorial(client, path_properti):
	"""
	Test rilis tutorial
	- menjarah dengan konfigurasi
	- menjarah dengan konten markdown
	url: `/ <tutorial> /`
	"""
	assert os.path.exists("{}/{}.html".format(
		path_properti['template'], 'tutorial'))
	site_config = get_config()
	for daftar in daftar_tutorial():
		t_config = get_config("{}.yaml".format(daftar))
		req = client.get("/{}/".format(daftar))
		soup = Soup(req.data, 'html.parser')

		if not site_config[daftar]['rilis']:
			continue
		# konfigurasi harus ada
		assert t_config != None

		# Data-data yang harus ada
		## Judul tutorial
		judul = soup.find("div", attrs={
			"class":"judul".format(daftar)})
		assert site_config[daftar]['title'] in judul.text.strip()
		## Ikon
		ikon = judul.find("i")
		assert site_config[daftar]['icon'] in ikon['class']

		jlh_cabang = len([x for x in t_config if x['rilis']])
		#jlh_baris
		baris = soup.find_all("div", attrs={'class':'contentMe'})
		if (jlh_cabang % 4 != 0) or (jlh_cabang < 4):
			jlh_baris = int(jlh_cabang / 4) + 1
			assert len(baris) == jlh_baris
		else:
			assert len(baris) == (jlh_cabang / 4)

		for cabang in t_config:
			nama_class = "cabang-tutorial-{}".format(cabang['title'])
			konten = soup.find('div',attrs={'id': nama_class})

			# deskripsi: mungkin berisi tag html
			if not cabang['rilis']:
				assert konten == None
			else:
				P = konten.find('p')
				assert Soup(cabang['desc'], 'html.parser').text\
					in P.text
Ejemplo n.º 5
0
def daftar_tutorial():
	site_config = get_config()
	for conf in site_config:
		if conf in ["title", "desc", "baseurl"]:
			continue
		else:
			yield conf
Ejemplo n.º 6
0
def get_konf_cabang(tut, cab):
    data = app.get_config("{}.yaml".format(tut))
    for d in data:
        if d['nama'] == cab:
            konf = d
            break
    return konf
Ejemplo n.º 7
0
def main():
    config = get_config()
    url = f"{config['url']}/{config['bot_token']}"
    requests.post(get_url("setWebhook"), data={"url": url})
    r = requests.get(get_url("getWebhookInfo"))
    pprint(r.status_code)
    pprint(r.json())
Ejemplo n.º 8
0
def app(request):
    """ Session wide test 'Flask' application """

    settings = get_config("app.settings.Testing")
    app = create_app(settings)
    ctx = app.app_context()
    ctx.push()
    yield app
    ctx.pop()
Ejemplo n.º 9
0
def test_cabang_dan_itemnya(client, path_properti):
	"""
	Test cabang tutorial
	Tes tidak dijalankan di semua konten cabang
	URL: / <tutorial> / <cabang> / 
	     / <tutorial> / <cabang> / <HEX>
	"""
	site_config = get_config()

	# tutorial
	konfigurasi_tutorial = {}
	for t in daftar_tutorial():
		t_config = get_config("{}.yaml".format(t))
		if site_config[t]['rilis']:
			konfigurasi_tutorial[t] = t_config

	for per_cabang in konfigurasi_tutorial:
		for conf in konfigurasi_tutorial[per_cabang]:
			#print(conf)
			#print()
			if not conf['rilis']: 
				continue
			c_config = get_config("{}/{}.yaml".format(
				per_cabang, conf['nama']))
			assert c_config != None, f'c_config != None; per_cabang={per_cabang} conf={conf["nama"]}'

			# Isi cabang 0x00 - 0xFF
			for h in hexnumber():
				md = page_file("pages", 
					per_cabang, conf['nama'], "{}.md".format(h))
				path = md.replace("pages/", "")
				req = client.get(path.replace(".md", ""))
				if not os.path.exists(md):
					assert req.status_code != 200
					continue
				assert req.status_code == 200
Ejemplo n.º 10
0
 def get(self):
     google_user = users.get_current_user()
     type_code_value = GoogleAccountType.get_code()
     open_id_value = google_user.federated_identity()
     account_key_name = Account.create_key_name(type_code=type_code_value,\
                                                 open_id=open_id_value)
     account = Account.get_by_key_name(account_key_name)
     if account == None:
         account = Account(key_name=account_key_name,\
                             type_code=type_code_value,\
                             open_id=open_id_value,\
                             email=google_user.email(),\
                             nickname=google_user.nickname())
         account.put()
     if account.canBindUser():
         add_account_to_bind_list(account)
         self.redirect(app.get_config().get('user/bind_user_url'))
     set_current_user(account.user)
Ejemplo n.º 11
0
def parse_options():
    """Parses command line options for Flask.

    Returns:
    Config instance to pass into create_app().
    """
    settings_class_string = {
        'prod': 'app.settings.Production',
        'dev': 'app.settings.Development',
        'testing': 'app.settings.Testing'
    }
    # Figure out which class will be imported.
    config_class_string = settings_class_string['dev']
    if OPTIONS['--env']:
        config_class_string = settings_class_string[OPTIONS['--env']]

    config_obj = get_config(config_class_string)

    return config_obj
Ejemplo n.º 12
0
    def test_get_config_with_valid_yaml(self):
        fake_config = StringIO("""Metrics:
        - Namespace: "DM-RequestTimeBuckets"
          MetricName: "preview-antivirus-api-request-times-0"
          Statistics: "Sum"
          Dimensions: {}
          Options:
            Formatter: 'cloudwatch.request_time_buckets.preview.antivirus-api.request_time_bucket_0.%(statistic)s'
        - Namespace: "DM-RequestTimeBuckets"
          MetricName: "preview-antivirus-api-request-times-1"
          Statistics: "Sum"
          Dimensions: {}
          Options:
            Formatter: 'cloudwatch.request_time_buckets.preview.antivirus-api.request_time_bucket_1.%(statistic)s'
        """)

        with mock.patch('app.open', return_value=fake_config):
            config_dict = get_config()

        assert config_dict == {
            'Metrics': [{
                'Namespace': 'DM-RequestTimeBuckets',
                'MetricName': 'preview-antivirus-api-request-times-0',
                'Statistics': 'Sum',
                'Dimensions': {},
                'Options': {
                    'Formatter':
                    'cloudwatch.request_time_buckets.preview.antivirus-api.'
                    'request_time_bucket_0.%(statistic)s'
                }
            }, {
                'Namespace': 'DM-RequestTimeBuckets',
                'MetricName': 'preview-antivirus-api-request-times-1',
                'Statistics': 'Sum',
                'Dimensions': {},
                'Options': {
                    'Formatter':
                    'cloudwatch.request_time_buckets.preview.antivirus-api.'
                    'request_time_bucket_1.%(statistic)s'
                }
            }]
        }
Ejemplo n.º 13
0
import re
from datetime import datetime, date
from .context import Context
from .transaction import TRA
from .doc_detail import Detail_service1, Detail_service2
from app import get_config, Constants as C

_glatency1 = int(get_config('LAYTENCY_TIME/board_read_article'))
_gmin_value = get_config('COMMON/min_count_of_total_articles')
_gsel_month = int(get_config('COMMON/sel_month'))


class Board_service(TRA):
    def __init__(self):
        super().__init__('받은문서목록')
        self.context = Context()

    def _initialize(self):
        self._top = self.context.auto.PaneControl(searchDepth=1,
                                                  Name=self.name("웹EDI"))
        self.home = self.context.auto.PaneControl(searchDepth=1,
                                                  Name=self.name("국민건강보험 EDI"))
        self.detail_service = {
            C.Biz: Detail_service1(),
            C.Idz: Detail_service2()
        }
        self.bbs_title = set()

    def req(self):
        self._initialize()
Ejemplo n.º 14
0
import logging
from decouple import config

from app import create_app, get_config

settings_class_string = {
    "prod": "app.settings.Production",
    "dev": "app.settings.Development",
    "testing": "app.settings.Testing",
}

logging.basicConfig(level=logging.DEBUG)

handler = logging.StreamHandler()
handler.setLevel(logging.DEBUG)
handler.setFormatter(logging.Formatter(logging.DEBUG))

env = config("FLASK_ENV", default="dev")
settings = get_config(settings_class_string[env])
app = create_app(config=settings)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)
Ejemplo n.º 15
0
from .context import Context
from .transaction import TRA
from .pdfprinting import Printing_service1, Printing_service2
from app import get_config

_glatency1 = get_config('LAYTENCY_TIME/detail_doc_print_button', 0)


# 사업장고지내역서
class Detail_service1(TRA):
    def __init__(self):
        super().__init__('게시물세부화면')
        self.context = Context()

    def _initialize(self):
        self._top = self.context.auto.PaneControl(searchDepth=1,
                                                  Name=self.name("웹EDI"))
        self.printing_service = Printing_service1()

    def req(self):
        self._initialize()

        self.begin("개시")
        self.act(self._top, 'activate')
        self.act(self._top.ImageControl(searchDepth=16, Name="img_tab2"))
        self.checkAndRetry()

        self.wait(int(_glatency1))

        # 출력버튼 클릭
        self.act(self._top.ImageControl(searchDepth=16, Name="img_print"),
Ejemplo n.º 16
0
 def test_extends_config(self):
     config = app.get_config()
     config.extends(CONFIG_1)
     config.extends(CONFIG_2)
     self.assertEqual(config.configs, CONFIG)
Ejemplo n.º 17
0
 def test_get(self):
     config = app.get_config()
     self.assertEqual(config.get("modules/test/version"), "0.1")
     self.assertEqual(config.get("modules/t2/version"), "0.2")
     self.assertEqual(config.get("t2/abc"), "rrr")
     self.assertEqual(config.get("t2/ert"), "qqqq")
Ejemplo n.º 18
0
# encoding: utf-8
# -*- coding: utf-8 -*-
from os.path import join

from openpyxl import load_workbook

from app import get_config, TMP_OUT
from gen.ctcxml import get_header
from gen.xsd import xls2xsd

EXCEL_PATH = unicode(get_config(__file__, 'excel_path'))
SHEET_NAME = get_config(__file__, 'sheet_name')


def get_cs_type(metadata):
    q = str(metadata).lower()
    if q == "dynamic" or q == 'code2':
        return "string"
    elif q == "int4" or q == "int10":
        return "int"
    elif q == "int20":
        return "long"
    elif q == "decimal2" or q == "decimal6":
        return 'decimal'
    elif q == "datetime" or q == "date":
        return 'DateTime'
    elif q == "boolean":
        return 'bool'
    else:
        return metadata
Ejemplo n.º 19
0
# encoding: utf-8
# -*- coding: uft-8 -*-

import openpyxl

from app import get_config, write_file
from gen import render_template
from gen.ctcxml import get_sheet_data

template_name = 'xsd.html'
excel_path = unicode(get_config(__file__, 'excel_path'))
sheet_name = unicode(get_config(__file__, 'sheet_name'))


def get_xsd_type(metadata, ctc_type):
    if ctc_type is None:
        ret = {
            'dynamic': 'xs:string',
            'int4': 'xs:int',
            'int10': 'xs:int',
            'int20': 'xs:long',
            'boolean': 'xs:boolean',
            'decimal2': 'xs:decimal',
            'decimal6': 'xs:decimal',
            'datetime': 'xs:dateTime',
            'code2': 'string'
        }[str(metadata).lower()]
    else:
        ret = ctc_type + 'Type'
    return ret
Ejemplo n.º 20
0
def get_login_urls():
    account_types = app.get_config().get('user/account_types')
    login_urls = []
    for account_type in account_types.values():
        login_urls.append(account_type.get_login_url())
    return login_urls
Ejemplo n.º 21
0
import datetime

from peewee import Model, CharField, IntegerField, DateTimeField, ForeignKeyField, AutoField, UUIDField
from peewee import PostgresqlDatabase

from app import get_config

# database = SqliteDatabase('vehicle_stats.db', 'Pooling=true')

config = get_config('../app/config.ini')

host = config.get("db", "POSTGRES_HOST")
port = config.get("db", "POSTGRES_PORT")
user = config.get("db", "POSTGRES_USER")
passw = config.get("db", "POSTGRES_PASSW")
db = config.get("db", "POSTGRES_DB")
database = PostgresqlDatabase(db,
                              user=user,
                              password=passw,
                              host=host,
                              port=port)


class BaseModel(Model):
    class Meta:
        database = database


class VehicleEventSummary(BaseModel):
    id = UUIDField(primary_key=True)
    vehicle = CharField()
Ejemplo n.º 22
0
# encoding: utf-8
# -*- coding: utf-8 -*-

import re
from os import listdir
from xml.etree import ElementTree as et

from app import get_config, read_to_lines

current_version = int(get_config(__file__, 'version'))
dir_contract_xml = get_config(__file__, 'dir_contract_xml')
dir_contract = get_config(__file__, 'dir_contract')
path_service_items = get_config(__file__, 'path_service_items')
path_version_map = get_config(__file__, 'path_version_map')


def get_version_value(version):
    version_min_value = 584
    return int(version) - version_min_value


def read_contract_file(dir, filename, request_service_map):
    '''读取契约文件'''

    version_set = set()
    for line in read_to_lines(filename, dir):
        if 'DatagramField' in line:
            match = re.search('\s*\[DatagramField.*Version\s=\s(?P<ver>\d+).*\]\s*', line)
            if match:
                version = int(match.group('ver'))
                if version > 0:
Ejemplo n.º 23
0
    def test_get_config_with_invalid_yaml(self):
        fake_config = StringIO("""}I am not valid yaml!""")
        with mock.patch('app.open', return_value=fake_config), pytest.raises(
                yaml.YAMLError):

            get_config()
Ejemplo n.º 24
0
class CeleryDBAdapter:
    app_config = get_config()[SERVER_MODE]
    db_engine = create_engine(app_config.SQLALCHEMY_DATABASE_URI,
                              poolclass=NullPool)
    session = scoped_session(sessionmaker(autocommit=False, bind=db_engine))
Ejemplo n.º 25
0
import sys

# from docopt import docopt
from app import create_app, get_config
from app.providers.database import db

# OPTIONS = docopt(__doc__) if __name__ == '__main__' else dict()
SETTINGS_CLASS_STRING = {
    "prod": "app.settings.Production",
    "dev": "app.settings.Development",
    "testing": "app.settings.Testing",
}


if __name__ == "__main__":
    env = sys.argv.pop(1)
    settings = get_config(SETTINGS_CLASS_STRING[env])
    app = create_app(settings)
    db.init_app(app)
    db.cli.run()
Ejemplo n.º 26
0
class Task(CELERY.Task):
    config = get_config()[SERVER_MODE]
    socket_io = None
    job = None

    # pylint: disable=unused-argument
    def run(self, previous_task_return_value, job_type: str, job_id: int,
            **kwargs):
        # The previous_task_return_value argument is required by celery chain method
        # as it uses partial argument rule
        signal.signal(signal.SIGTERM, lambda signum, frame: self.terminate())
        self.socket_io = SocketIO(message_queue=self.config.broker_url)
        data = kwargs['data'] if 'data' in kwargs else {}
        progress_weight = kwargs[
            'progress_weight'] if 'progress_weight' in kwargs else 1
        self.job = JobFromDBFactory.create_job(job_type, job_id,
                                               self.socket_io, data,
                                               progress_weight, self)
        self.job.set_task_id(self.request.id)
        self.job.run()

    # pylint: disable=unused-argument
    @staticmethod
    def after_return(*args):
        CeleryDBAdapter.session.remove()

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        log.debug('[ TASK %s FAILED ] ', task_id)
        log.debug('[ TASK ARGS ] : %s', args)
        log.debug('[ TASK KWARGS ] : %s', kwargs)
        if isinstance(exc, GeneralError):
            message = str(exc)
            error_code = exc.get_error_code()
        elif isinstance(exc, SQLAlchemyError):
            message = 'Unable to update information in database'
            error_code = CodeRegistry.get_database_error_code()
        else:
            message = str(exc)
            error_code = 500
        log.error('Server Exception', exc_info=einfo)
        FeedEmitMessage.socket_io = self.socket_io
        if self.job:
            safe_run(self.job.on_failure)()
        FeedEmitMessage.emit(error_code, message)
        gc.collect()

    # pylint: disable=unused-argument
    @staticmethod
    def on_success(*args):
        gc.collect()

    def terminate(self):
        self.request.callbacks = None
        self.request.chain = None
        for pid in self.job.subprocess:
            try:
                os.kill(pid, 0)
            except OSError:
                pass
            else:
                os.kill(pid, signal.SIGTERM)
        get_celery().control.revoke(self.request.id,
                                    terminate=True,
                                    signal='SIGKILL')
        CeleryDBAdapter.session.remove()
        sys.exit(1)
Ejemplo n.º 27
0
# encoding: utf-8
# -*- coding: uft-8 -*-

import time
from os import listdir, mkdir
from os.path import exists, join, splitext
from xml.etree import ElementTree as et

from app import get_config, write_file
from gen import render_template

template_name = 'ctccode.html'

DIR_ROOT = get_config(__file__, 'root')


def escape(attrib_val):
    return str(attrib_val).replace('\\', '/').replace('"', '\\"')


def parse_head(head):
    ret = []
    t = {
        "name": head["name"],
        "prop": get_props(head["items"])
    }
    ret.append(t)
    ret.extend(parse_items(head["items"]))
    return ret

Ejemplo n.º 28
0
# encoding: utf-8
# -*- coding: utf-8 -*-
from app import get_config, write_file, TMP_OUT
from gen import render_template

tpl_name = 'detail_loader.html'
bizname = get_config(__file__, 'bizname')


def main():
    page = render_template(tpl_name=tpl_name, bizname=bizname)
    if page is not None:
        write_file('{0}CardDetailLoader.cs'.format(bizname), page, TMP_OUT)

    print 'done'


if __name__ == '__main__':
    main()
Ejemplo n.º 29
0
from abc import ABCMeta, abstractmethod
import uiautomation as auto
import time
from app import get_config
from .context import Context

RETRY_MAX = int(get_config('COMMON/retry_max', 0))
_gchrome_name_prefix = get_config('WEB_BROWSER/chrome_name_prefix', 0)


class TRA(metaclass=ABCMeta):
    def __init__(self, id):
        self.id = id
        self.context = Context()
        self.__initialize()

    def __initialize(self):
        self.cur = ''
        self.cr_flag = False
        self.err = False
        self.tr_flag = False

    @abstractmethod
    def req(self):
        pass

    def begin(self, title):
        print("[{0}]<{1}>".format(self.id, title))

    #c:control, h:n-th, v:depth, _a:action
    def take(self, c, h=0, v=0, _a=None, **kargs):
Ejemplo n.º 30
0
import json, os
from .AESCipher import AESCipher
from app import get_config

_glogininfo = get_config('COMMON/logininfo')
_gcertificate = get_config('COMMON/certificate')
_gcertificate_sub = get_config('COMMON/certificate_sub')


def _merge():
    _lcompany = list()
    with open(_gcertificate, 'r', encoding='utf-8') as f:
        while True:
            _record = f.readline()
            if not _record: break

            _a = _record.split(',')
            name, pkey = _a[0], _a[1].replace('\n', '')

            _lcompany.append({'name': name, 'passwd': pkey})

    _dmanager = dict()
    with open(_gcertificate_sub, 'r', encoding='utf-8') as f:
        while True:
            _record = f.readline()
            if not _record: break

            _a = _record.split(',')
            name, id, pw, code = _a[0], _a[1], _a[2], _a[3].replace('\n', '')

            if name not in _dmanager:
Ejemplo n.º 31
0
def test_get_config():
    config = get_config()
    assert config.ENV == 'testing'

    config = get_config(config_name='development')
    assert config.ENV == 'development'
Ejemplo n.º 32
0
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
"""
from celery import Celery

from app import get_config
from config.constants import SERVER_MODE


def get_celery() -> Celery:
    return get_celery.CELERY


get_celery.CELERY = Celery(backend=get_config()[SERVER_MODE].celery_backend_url,
                           broker=get_config()[SERVER_MODE].broker_url)


def init_celery_app(app):
    celery = get_celery()
    celery.conf.update(app.config)

    return celery
Ejemplo n.º 33
0
 def test_get_routers(self):
     routers = app.get_config().get("routers")
     self.assertTrue(len(routers) > 1)
Ejemplo n.º 34
0
import os
from .context import Context
from .transaction import TRA
from app import get_config

_gdownload_folder = get_config('COMMON/download_folder', 0)
_glaytency1 = get_config('LAYTENCY_TIME/printing_preview_', 0)
_glaytency2 = get_config('LAYTENCY_TIME/printing_save', 0)


class Printing_service1(TRA):
    def __init__(self):
        super().__init__('PDF다운로드')
        self.context = Context()

    def _initialize(self):
        if 'code' in self.context.info:
            self.title = '[{0}-{1}]{2}'.format(self.context.info['name'],
                                               self.context.info['code'],
                                               self.context.title)
        else:
            self.title = '[{0}]{2}'.format(self.context.info['name'],
                                           self.context.title)

        self._top = self.context.auto.PaneControl(searchDepth=1,
                                                  Name=self.name("미리보기"))

    def req(self):
        self._initialize()

        self.begin("개시")
Ejemplo n.º 35
0
# encoding: utf-8
# -*- coding: uft-8 -*-
import re
import sys

from app import get_config

__author__ = 'chengz'

reload(sys)
sys.setdefaultencoding("utf-8")

out_match_file = get_config(__file__, 'out_match_file')
out_unmatched_file = get_config(__file__, 'out_unmatched_file')
in_data_file = get_config(__file__, 'in_data_file')


def is_match(left, right):
    unused = ['楼', '区', '柜台', '岛', '/']
    splicers = [',', '、']

    for word in unused:
        left = left.replace(word, '')
        right = right.replace(word, '')

    if any(x in left for x in splicers):
        for y in re.split('|'.join(splicers), left):
            if is_match(y, right):
                return True
        return False
Ejemplo n.º 36
0
from app import get_logger, get_config
import math
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from app import utils
from app.models import CfgNotify
from app.main.forms import CfgNotifyForm
from . import main

logger = get_logger(__name__)
cfg = get_config()

# 通用列表查询
def common_list(DynamicModel, view):
    # 接收参数
    action = request.args.get('action')
    id = request.args.get('id')
    page = int(request.args.get('page')) if request.args.get('page') else 1
    length = int(request.args.get('length')) if request.args.get('length') else cfg.ITEMS_PER_PAGE

    # 删除操作
    if action == 'del' and id:
        try:
            DynamicModel.get(DynamicModel.id == id).delete_instance()
            flash('删除成功')
        except:
            flash('删除失败')

    # 查询列表
    query = DynamicModel.select()
    total_count = query.count()
Ejemplo n.º 37
0
import json
import uiautomation as auto
import subprocess as ps
from app import get_config
from .AESCipher import AESCipher
import time

_gchrome_path = get_config('WEB_BROWSER/chrome')
_gchrome_keyword = get_config('WEB_BROWSER/chrome_search_keyword')
_gchrome_name_prefix = get_config('WEB_BROWSER/chrome_name_prefix')
_gcertificate = get_config('COMMON/logininfo')

class RPA:
    
    def __init__(self,**kargs):
        self.auto = auto
        self.site(**kargs)
        
    def site(self, **kargs):
        self.url = kargs['url']
        self.url_title = kargs['title']

    def close_page(self):
        top = self.auto.PaneControl(searchDepth=1, Name=self.name(self.url_title))

        _w = top.PaneControl(searchDepth=2, Name='Chrome')
        _close_b = _w.ButtonControl(searchDepth=2, Name='닫기')
        if _close_b.Exists(0,0):
            _close_b.Click()

    def open_page(self):
Ejemplo n.º 38
0
def main():
    application = webapp.WSGIApplication(get_config().get("routers"), debug=True)
    util.run_wsgi_app(application)
Ejemplo n.º 39
0
from flask import render_template, redirect, url_for, flash, request
from flask_login import login_required, current_user
from flask import jsonify
from app import utils
from app.models import CfgNotify, Client
from app.main.forms import CfgNotifyForm
from app.utils import load_mapping, import_excel
from peewee import SQL
from werkzeug.utils import secure_filename
from . import main
import os
from conf.config import config


logger = get_logger(__name__)
cfg = get_config()


# 通用列表查询
def common_list(DynamicModel, view):
    # 接收参数
    action = request.args.get('action')
    id = request.args.get('id')
    page = int(request.args.get('page')) if request.args.get('page') else 1
    length = int(request.args.get('length')) if request.args.get(
        'length') else cfg.ITEMS_PER_PAGE

    # 删除操作
    if action == 'del' and id:
        try:
            DynamicModel.get(DynamicModel.id == id).delete_instance()
Ejemplo n.º 40
0
# encoding: utf-8
# -*- coding: uft-8 -*-

import time
from os import mkdir
from os.path import exists, join

import openpyxl

from app import get_config, write_file
from gen import render_template

template_name = 'ctcxml.html'
excel_path = unicode(get_config(__file__, 'excel_path'))
ROOT = get_config(__file__, 'root')
only_mark = bool(int(get_config(__file__, 'only_mark')))


def is_not_default_color(font):
    while_color = '00000000'
    return font.color.value != while_color


def get_svc_metadata(row):
    service_code = row[1]
    service_name = row[2]
    service_desc = row[3]
    if service_code.value:
        return {
            'code': service_code.value,
            'name': service_name.value,
Ejemplo n.º 41
0
from .transaction import TRA
from .context import Context
from app import get_config

_gmedia_type = get_config('COMMON/media_type')
_gusb_name = get_config('COMMON/usb_media_name')
_gsite_name = get_config('SITE/name')
_glatency1 = get_config('LAYTENCY_TIME/login_certificate')

class Login_service(TRA):
    def __init__(self):
        super().__init__('LOGIN')
        self.context = Context()
       
    def _initialize(self):
        self.top = self.context.auto.PaneControl(searchDepth=1, Name=self.name(_gsite_name))

    def req(self):
        self._initialize()

        self.begin("개시")
        self.act(self.top, 'activate')
        self.act(self.top.ImageControl(searchDepth=7,Name='공동인증서 로그인'))
        self.checkAndRetry()
        #대기시간
        self.wait(int(_glatency1))

        self.act(self.top.ImageControl(searchDepth=7,Name='공동인증서 로그인'), 'click')
        
        if _gmedia_type=='1': self._hard_disk()
        elif _gmedia_type=='2': self._usb_disk()
Ejemplo n.º 42
0
import glob,os
from controller import Cntl
from model import RPA
from view import View
from app import get_config

_gurl = get_config('SITE/url')
_gsite_name = get_config('SITE/name')
_gdown = get_config('COMMON/download_folder')

if __name__== '__main__':

    view = View()
    model = RPA(url=_gurl, title=_gsite_name)
    cntl = Cntl()
    
    view.handler(cntl)
    view.model(model)
    cntl.model(model) 

    view.mainloop()