ConDict

Check-in [f13acd25c6]
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:finish add pattern
Timelines: family | ancestors | descendants | both | testing
Files: files | file ages | folders
SHA1:f13acd25c6dc32635362755e731a3a76b568209e
User & Date: zorro 2012-09-08 11:23:32
Context
2012-09-08
11:33
change comments check-in: a055a3c430 user: zorro tags: testing
11:23
finish add pattern check-in: f13acd25c6 user: zorro tags: testing
2012-09-06
18:08
start add-function check-in: 8ed6cdeb7b user: zorro tags: testing
Changes
Hide Diffs Side-by-Side Diffs Ignore Whitespace Patch

Changes to aside.py.

     1      1   #!/usr/bin/env python3
     2      2   #-*- coding: utf-8 -*-
     3      3   
     4         -import re, configparser, json
            4  +import re, configparser, json, signal
     5      5   from urllib import request
     6      6   
     7         -YANDEX_TRANSLATE = "http://translate.yandex.net/api/v1/tr.json/translate?lang="
            7  +YANDEX_TRANSLATE_JSON = "http://translate.yandex.net/api/v1/tr.json/translate?lang="
            8  +TEST_CONNECT = "http://ya.ru/"
     8      9   
     9     10   def get_config_data(filename):
    10     11       result = {'database': None, 'defuser': None}
    11     12       config = configparser.ConfigParser()
    12     13       try:
    13     14           config.read(filename)
    14     15           result['database'] = config['database']['dbname']
................................................................................
    22     23       # return [command, str_params]
    23     24       command = result.split(" ", 1)
    24     25       if len(command) == 1:
    25     26           command.append([])
    26     27       return command
    27     28   
    28     29   def get_translate(for_translate, trans_type):
           30  +    global YANDEX_TRANSLATE_JSON
    29     31       result = False
    30     32       prepate_url = request.pathname2url(for_translate)
    31     33       trans_types = {'en': 'en-ru', 'ru': 'ru-en'}
    32         -    prepate_url = YANDEX_TRANSLATE + trans_types[trans_type] + "&text=" + prepate_url
           34  +    prepate_url = YANDEX_TRANSLATE_JSON + trans_types[trans_type] + "&text=" + prepate_url
    33     35       try:
    34     36           conn = request.urlopen(prepate_url)
    35     37       except Exception as e:
    36     38           print("Not connection\nError:")
    37     39           print(e)
    38     40           return result
    39     41       if conn.status == 200:
................................................................................
    40     42           try:
    41     43               from_url = conn.read().decode('utf-8')
    42     44               result = json.loads(from_url)
    43     45           except Exception as e:
    44     46               print(e)
    45     47       conn.close()
    46     48       return result
           49  +
           50  +def get_test_connection():
           51  +    global TEST_CONNECT
           52  +    try:
           53  +        conn = request.urlopen(TEST_CONNECT)
           54  +        result = True if conn.getcode() == 200 else False
           55  +    except Exception as e:
           56  +        print('Test connection False,', e)
           57  +        return False
           58  +    conn.close()
           59  +    return result 

Changes to condt.py.

    10     10   
    11     11   class IncorrectDbData(Exception): pass
    12     12   
    13     13   class BaseConDict(object):
    14     14       """Base Console Dictionary class"""
    15     15       def __init__(self, name, dbfile):
    16     16           self.connect = sqlite3.connect(dbfile)
           17  +        self.online = False
    17     18           self.name = name
    18     19       def __repr__(self):
    19     20           return "<ConDict object for {0}>".format(self.name)
    20     21       def __str__(self):
    21     22           return "<ConDict object for {0}>".format(self.name)
    22     23       def __bool__(self):
    23     24           valid = True if self.user_id else False
................................................................................
    30     31       COMMANDS = {'.help': {'desc': 'list commands', 'command': None}, 
    31     32           '.chname': {'desc': 'change current user name', 'command': None},
    32     33           '.chpassword': {'desc': 'change current password', 'command': None},
    33     34           '.list': {'desc': 'list users words', 'command': None},
    34     35           '.en': {'desc': 'dictionary mode English to Russian', 'command': None},
    35     36           '.ru': {'desc': 'dictionary mode Russian to English', 'command': None},
    36     37           '.add': {'desc': 'add new words', 'command': None},
           38  +        '.connect': {'desc': 'test connection', 'command': None},
    37     39           # '.edit': {'desc': 'edit words', 'command': None},
    38     40           # '.del': {'desc': 'delete words', 'command': None},
    39     41           '.exit': {'desc': 'quit from program', 'command': None},
    40     42           }
    41     43       def __init__(self, name, dbfile):
    42     44           super().__init__(name, dbfile)       
    43     45           self.__pcounter = 3
    44     46           self.init_command()
    45     47           self.user_id = self.get_user()
           48  +        self.command_connect()
    46     49   
    47     50       def get_user(self):
    48     51           sqlstr="SELECT id FROM user WHERE name=(?) AND password=(?)"
    49     52           cur = self.connect.cursor()
    50     53           ch_user_id = self.check_name(cur)
    51     54           if ch_user_id:
    52     55               ch_user_id = ch_user_id[0]
................................................................................
    62     65           self.COMMANDS['.exit']['command'] = self.command_exit
    63     66           self.COMMANDS['.chname']['command'] = self.command_chname
    64     67           self.COMMANDS['.chpassword']['command'] = self.command_chpassword
    65     68           self.COMMANDS['.list']['command'] = self.command_list
    66     69           self.COMMANDS['.en']['command'] = self.command_en
    67     70           self.COMMANDS['.ru']['command'] = self.command_ru
    68     71           self.COMMANDS['.add']['command'] = self.command_add
           72  +        self.COMMANDS['.connect']['command'] = self.command_connect
    69     73   
    70     74       def hash_pass(self, password):
    71     75           result = bytes(password.strip() + SALT, 'utf-8')
    72     76           result = bytes(hashlib.md5(result).hexdigest(), 'utf-8')
    73     77           return hashlib.sha1(result).hexdigest()
    74     78   
    75     79       def check_name(self, cur):
................................................................................
   202    206       def command_en(self, text):
   203    207           print(self.command_enru(text, 'en'))
   204    208           return 'en'
   205    209       def command_ru(self, text):
   206    210           print(self.command_enru(text, 'ru'))
   207    211           return 'ru'
   208    212       def command_enru(self, text, tr_type):
          213  +        if not self.online:
          214  +            return "Offline, please test connect with '.connect' command"
   209    215           result = get_translate(text, tr_type)
   210    216           if not result or result['code'] != 200:
          217  +            self.command_connect()
   211    218               return "Error, not foud translate"
   212    219           return result['text']
   213    220   
   214    221       def command_list(self, pattern=None):
   215    222           cur = self.connect.cursor()
   216    223           sql_list = "SELECT `translate`.`id`, `term`.`en`, `translate`.`rus`, `progress`.`all`, `progress`.`error` FROM `translate` LEFT JOIN `term` ON (`translate`.`term`=`term`.`token`) LEFT JOIN `progress` ON (`progress`.`translate_id`=`translate`.`id`) WHERE `translate`.`user_id`=(?) "
   217    224           params = (self.user_id,)
................................................................................
   268    275                   if cur.fetchone():
   269    276                       print('Words add already.')
   270    277                       break
   271    278                   sql_list1 = "INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))"
   272    279                   cur.execute(sql_list1, (token, en))
   273    280                   sql_list2 = "INSERT INTO `translate` (`term`, `user_id`, `rus`) VALUES (?, ?, ?)"
   274    281                   cur.execute(sql_list2, (token, self.user_id, ru))
          282  +                sql_list3 = "INSERT INTO `progress` (`translate_id`) VALUES (?)"
          283  +                cur.execute(sql_list3, (cur.lastrowid,))
   275    284               except (sqlite3.DatabaseError, IncorrectDbData) as er:
   276    285                   if DEBUG: print(er)
   277    286                   print('Incorrect information, change data')
   278    287                   ent = input('Do you wand enter new words [Y/n]?')
   279    288                   if ent in ('n', 'N'):
   280    289                       break
   281    290                   continue
................................................................................
   285    294           cur.close()
   286    295           return 'add'
   287    296   
   288    297       def command_edit(self, translate_id):
   289    298           pass
   290    299       def command_delete(self, id_or_pattern):
   291    300           pass
          301  +
          302  +    def command_connect(self, arg=None):
          303  +        result = get_test_connection()
          304  +        if result:
          305  +            print("Ok connection")
          306  +        else:
          307  +            print("Error connection")
          308  +        self.online = result
          309  +        return 'connect'

Changes to db.sqlite.

cannot compute difference between binary files

Changes to main.py.

     2      2   #-*- coding: utf-8 -*-
     3      3   
     4      4   from aside import *
     5      5   from condt import Condt
     6      6   import getpass, os
     7      7   
     8      8   CONF_NAME = 'condt.conf' 
     9         -PREFIX = "{0}@ConDict>>>"
            9  +PREFIX = "{0}@ConDict[{1}]>>>"
    10     10   WELCOM = """****************************************************
    11     11   *** Good day.                                    ***
    12     12   *** For help, use the command ".help", nice work.***
    13     13   ****************************************************"""
    14     14   
    15     15   def main():
    16     16       global CONF_NAME, PREFIX
................................................................................
    24     24       # create object
    25     25       account = Condt(user, config['database'])
    26     26       if not account:
    27     27           print('Validation error, by...')
    28     28           return 0
    29     29       print(WELCOM)
    30     30       while (True):
    31         -        prefix = PREFIX.format(account.name)
           31  +        conn_status = 'online' if account.online else 'offline'
           32  +        prefix = PREFIX.format(account.name, conn_status)
    32     33           command = input(prefix)
    33     34           get_command = account.handling_command(command)
    34     35           if get_command is None:
    35     36               print('Sorry, unknown command: "{0}"\nuse ".help" for more information'.format(command))
    36     37               continue
    37     38           if not get_command:
    38     39               print("By {0}!".format(account.name))