ConDict

Check-in [f13acd25c6]
Login

Check-in [f13acd25c6]

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.590
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
Unified Diff Ignore Whitespace Patch
Changes to aside.py.
1
2
3
4
5
6
7

8
9
10
11
12
13
14
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import re, configparser, json
from urllib import request

YANDEX_TRANSLATE = "http://translate.yandex.net/api/v1/tr.json/translate?lang="


def get_config_data(filename):
    result = {'database': None, 'defuser': None}
    config = configparser.ConfigParser()
    try:
        config.read(filename)
        result['database'] = config['database']['dbname']



|


|
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import re, configparser, json, signal
from urllib import request

YANDEX_TRANSLATE_JSON = "http://translate.yandex.net/api/v1/tr.json/translate?lang="
TEST_CONNECT = "http://ya.ru/"

def get_config_data(filename):
    result = {'database': None, 'defuser': None}
    config = configparser.ConfigParser()
    try:
        config.read(filename)
        result['database'] = config['database']['dbname']
22
23
24
25
26
27
28

29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46











    # return [command, str_params]
    command = result.split(" ", 1)
    if len(command) == 1:
        command.append([])
    return command

def get_translate(for_translate, trans_type):

    result = False
    prepate_url = request.pathname2url(for_translate)
    trans_types = {'en': 'en-ru', 'ru': 'ru-en'}
    prepate_url = YANDEX_TRANSLATE + trans_types[trans_type] + "&text=" + prepate_url
    try:
        conn = request.urlopen(prepate_url)
    except Exception as e:
        print("Not connection\nError:")
        print(e)
        return result
    if conn.status == 200:
        try:
            from_url = conn.read().decode('utf-8')
            result = json.loads(from_url)
        except Exception as e:
            print(e)
    conn.close()
    return result


















>



|














>
>
>
>
>
>
>
>
>
>
>
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
    # return [command, str_params]
    command = result.split(" ", 1)
    if len(command) == 1:
        command.append([])
    return command

def get_translate(for_translate, trans_type):
    global YANDEX_TRANSLATE_JSON
    result = False
    prepate_url = request.pathname2url(for_translate)
    trans_types = {'en': 'en-ru', 'ru': 'ru-en'}
    prepate_url = YANDEX_TRANSLATE_JSON + trans_types[trans_type] + "&text=" + prepate_url
    try:
        conn = request.urlopen(prepate_url)
    except Exception as e:
        print("Not connection\nError:")
        print(e)
        return result
    if conn.status == 200:
        try:
            from_url = conn.read().decode('utf-8')
            result = json.loads(from_url)
        except Exception as e:
            print(e)
    conn.close()
    return result

def get_test_connection():
    global TEST_CONNECT
    try:
        conn = request.urlopen(TEST_CONNECT)
        result = True if conn.getcode() == 200 else False
    except Exception as e:
        print('Test connection False,', e)
        return False
    conn.close()
    return result 
Changes to condt.py.
10
11
12
13
14
15
16

17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

37
38
39
40
41
42
43
44
45

46
47
48
49
50
51
52

class IncorrectDbData(Exception): pass

class BaseConDict(object):
    """Base Console Dictionary class"""
    def __init__(self, name, dbfile):
        self.connect = sqlite3.connect(dbfile)

        self.name = name
    def __repr__(self):
        return "<ConDict object for {0}>".format(self.name)
    def __str__(self):
        return "<ConDict object for {0}>".format(self.name)
    def __bool__(self):
        valid = True if self.user_id else False
        return valid
    def __del__(self):
        self.connect.close()

class Condt(BaseConDict):
    """Condt - class for ConDict"""
    COMMANDS = {'.help': {'desc': 'list commands', 'command': None}, 
        '.chname': {'desc': 'change current user name', 'command': None},
        '.chpassword': {'desc': 'change current password', 'command': None},
        '.list': {'desc': 'list users words', 'command': None},
        '.en': {'desc': 'dictionary mode English to Russian', 'command': None},
        '.ru': {'desc': 'dictionary mode Russian to English', 'command': None},
        '.add': {'desc': 'add new words', 'command': None},

        # '.edit': {'desc': 'edit words', 'command': None},
        # '.del': {'desc': 'delete words', 'command': None},
        '.exit': {'desc': 'quit from program', 'command': None},
        }
    def __init__(self, name, dbfile):
        super().__init__(name, dbfile)       
        self.__pcounter = 3
        self.init_command()
        self.user_id = self.get_user()


    def get_user(self):
        sqlstr="SELECT id FROM user WHERE name=(?) AND password=(?)"
        cur = self.connect.cursor()
        ch_user_id = self.check_name(cur)
        if ch_user_id:
            ch_user_id = ch_user_id[0]







>




















>









>







10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

class IncorrectDbData(Exception): pass

class BaseConDict(object):
    """Base Console Dictionary class"""
    def __init__(self, name, dbfile):
        self.connect = sqlite3.connect(dbfile)
        self.online = False
        self.name = name
    def __repr__(self):
        return "<ConDict object for {0}>".format(self.name)
    def __str__(self):
        return "<ConDict object for {0}>".format(self.name)
    def __bool__(self):
        valid = True if self.user_id else False
        return valid
    def __del__(self):
        self.connect.close()

class Condt(BaseConDict):
    """Condt - class for ConDict"""
    COMMANDS = {'.help': {'desc': 'list commands', 'command': None}, 
        '.chname': {'desc': 'change current user name', 'command': None},
        '.chpassword': {'desc': 'change current password', 'command': None},
        '.list': {'desc': 'list users words', 'command': None},
        '.en': {'desc': 'dictionary mode English to Russian', 'command': None},
        '.ru': {'desc': 'dictionary mode Russian to English', 'command': None},
        '.add': {'desc': 'add new words', 'command': None},
        '.connect': {'desc': 'test connection', 'command': None},
        # '.edit': {'desc': 'edit words', 'command': None},
        # '.del': {'desc': 'delete words', 'command': None},
        '.exit': {'desc': 'quit from program', 'command': None},
        }
    def __init__(self, name, dbfile):
        super().__init__(name, dbfile)       
        self.__pcounter = 3
        self.init_command()
        self.user_id = self.get_user()
        self.command_connect()

    def get_user(self):
        sqlstr="SELECT id FROM user WHERE name=(?) AND password=(?)"
        cur = self.connect.cursor()
        ch_user_id = self.check_name(cur)
        if ch_user_id:
            ch_user_id = ch_user_id[0]
62
63
64
65
66
67
68

69
70
71
72
73
74
75
        self.COMMANDS['.exit']['command'] = self.command_exit
        self.COMMANDS['.chname']['command'] = self.command_chname
        self.COMMANDS['.chpassword']['command'] = self.command_chpassword
        self.COMMANDS['.list']['command'] = self.command_list
        self.COMMANDS['.en']['command'] = self.command_en
        self.COMMANDS['.ru']['command'] = self.command_ru
        self.COMMANDS['.add']['command'] = self.command_add


    def hash_pass(self, password):
        result = bytes(password.strip() + SALT, 'utf-8')
        result = bytes(hashlib.md5(result).hexdigest(), 'utf-8')
        return hashlib.sha1(result).hexdigest()

    def check_name(self, cur):







>







65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
        self.COMMANDS['.exit']['command'] = self.command_exit
        self.COMMANDS['.chname']['command'] = self.command_chname
        self.COMMANDS['.chpassword']['command'] = self.command_chpassword
        self.COMMANDS['.list']['command'] = self.command_list
        self.COMMANDS['.en']['command'] = self.command_en
        self.COMMANDS['.ru']['command'] = self.command_ru
        self.COMMANDS['.add']['command'] = self.command_add
        self.COMMANDS['.connect']['command'] = self.command_connect

    def hash_pass(self, password):
        result = bytes(password.strip() + SALT, 'utf-8')
        result = bytes(hashlib.md5(result).hexdigest(), 'utf-8')
        return hashlib.sha1(result).hexdigest()

    def check_name(self, cur):
202
203
204
205
206
207
208


209
210

211
212
213
214
215
216
217
    def command_en(self, text):
        print(self.command_enru(text, 'en'))
        return 'en'
    def command_ru(self, text):
        print(self.command_enru(text, 'ru'))
        return 'ru'
    def command_enru(self, text, tr_type):


        result = get_translate(text, tr_type)
        if not result or result['code'] != 200:

            return "Error, not foud translate"
        return result['text']

    def command_list(self, pattern=None):
        cur = self.connect.cursor()
        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`=(?) "
        params = (self.user_id,)







>
>


>







206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
    def command_en(self, text):
        print(self.command_enru(text, 'en'))
        return 'en'
    def command_ru(self, text):
        print(self.command_enru(text, 'ru'))
        return 'ru'
    def command_enru(self, text, tr_type):
        if not self.online:
            return "Offline, please test connect with '.connect' command"
        result = get_translate(text, tr_type)
        if not result or result['code'] != 200:
            self.command_connect()
            return "Error, not foud translate"
        return result['text']

    def command_list(self, pattern=None):
        cur = self.connect.cursor()
        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`=(?) "
        params = (self.user_id,)
268
269
270
271
272
273
274


275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291









                if cur.fetchone():
                    print('Words add already.')
                    break
                sql_list1 = "INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))"
                cur.execute(sql_list1, (token, en))
                sql_list2 = "INSERT INTO `translate` (`term`, `user_id`, `rus`) VALUES (?, ?, ?)"
                cur.execute(sql_list2, (token, self.user_id, ru))


            except (sqlite3.DatabaseError, IncorrectDbData) as er:
                if DEBUG: print(er)
                print('Incorrect information, change data')
                ent = input('Do you wand enter new words [Y/n]?')
                if ent in ('n', 'N'):
                    break
                continue
            else:
                self.connect.commit()
                break
        cur.close()
        return 'add'

    def command_edit(self, translate_id):
        pass
    def command_delete(self, id_or_pattern):
        pass
















>
>

















>
>
>
>
>
>
>
>
>
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
                if cur.fetchone():
                    print('Words add already.')
                    break
                sql_list1 = "INSERT INTO `term` (`token`, `en`) VALUES ((?), (?))"
                cur.execute(sql_list1, (token, en))
                sql_list2 = "INSERT INTO `translate` (`term`, `user_id`, `rus`) VALUES (?, ?, ?)"
                cur.execute(sql_list2, (token, self.user_id, ru))
                sql_list3 = "INSERT INTO `progress` (`translate_id`) VALUES (?)"
                cur.execute(sql_list3, (cur.lastrowid,))
            except (sqlite3.DatabaseError, IncorrectDbData) as er:
                if DEBUG: print(er)
                print('Incorrect information, change data')
                ent = input('Do you wand enter new words [Y/n]?')
                if ent in ('n', 'N'):
                    break
                continue
            else:
                self.connect.commit()
                break
        cur.close()
        return 'add'

    def command_edit(self, translate_id):
        pass
    def command_delete(self, id_or_pattern):
        pass

    def command_connect(self, arg=None):
        result = get_test_connection()
        if result:
            print("Ok connection")
        else:
            print("Error connection")
        self.online = result
        return 'connect'
Changes to db.sqlite.

cannot compute difference between binary files

Changes to main.py.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from aside import *
from condt import Condt
import getpass, os

CONF_NAME = 'condt.conf' 
PREFIX = "{0}@ConDict>>>"
WELCOM = """****************************************************
*** Good day.                                    ***
*** For help, use the command ".help", nice work.***
****************************************************"""

def main():
    global CONF_NAME, PREFIX








|







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#!/usr/bin/env python3
#-*- coding: utf-8 -*-

from aside import *
from condt import Condt
import getpass, os

CONF_NAME = 'condt.conf' 
PREFIX = "{0}@ConDict[{1}]>>>"
WELCOM = """****************************************************
*** Good day.                                    ***
*** For help, use the command ".help", nice work.***
****************************************************"""

def main():
    global CONF_NAME, PREFIX
24
25
26
27
28
29
30

31
32
33
34
35
36
37
38
    # create object
    account = Condt(user, config['database'])
    if not account:
        print('Validation error, by...')
        return 0
    print(WELCOM)
    while (True):

        prefix = PREFIX.format(account.name)
        command = input(prefix)
        get_command = account.handling_command(command)
        if get_command is None:
            print('Sorry, unknown command: "{0}"\nuse ".help" for more information'.format(command))
            continue
        if not get_command:
            print("By {0}!".format(account.name))







>
|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    # create object
    account = Condt(user, config['database'])
    if not account:
        print('Validation error, by...')
        return 0
    print(WELCOM)
    while (True):
        conn_status = 'online' if account.online else 'offline'
        prefix = PREFIX.format(account.name, conn_status)
        command = input(prefix)
        get_command = account.handling_command(command)
        if get_command is None:
            print('Sorry, unknown command: "{0}"\nuse ".help" for more information'.format(command))
            continue
        if not get_command:
            print("By {0}!".format(account.name))