Доступ к значению fun var одного файла в другой развлечение или за пределами развлечения другого python файла? - PullRequest
0 голосов
/ 05 августа 2020

У меня есть три python файлов. Проблема в том, что я пытаюсь получить доступ к переменной («имя пользователя»), определенной в sample.py в файле test.py, поэтому я могу использовать значение этой переменной или любой другой переменной и передать это в функцию, или если я могу напрямую получить доступ к любому значению переменной внутри функции (test_target) test.py

sample.py

from configparser import ConfigParser

parser = ConfigParser()
parser.read('config.ini')


def GetEnviornment():
    env = input("Enter Environment name : ") or 'Dev Site'
    return env

def GetConnectionString():
    env = GetEnviornment()
    username = parser.get(env, 'username')
    password = parser.get(env, 'password')
    dbname = parser.get(env, 'dbname')

    return "%s/%s@%s" % (username, password, dbname)

connection.py

import cx_Oracle
import sample

class Connection(cx_Oracle.Connection):

    def __init__(self):
        connectString = test.GetConnectionString()
        print("CONNECT to database")
        return super(Connection, self).__init__(connectString)

    def cursor(self):
        return Cursor(self)


class Cursor(cx_Oracle.Cursor):

    def execute(self, statement):
        print("EXECUTE", statement)
        return super(Cursor, self).execute(statement)

    def fetchall(self):
        print("FETCH ALL")
        return super(Cursor, self).fetchall()

test.py

from connection import *    
from sample import *

def test_target(user_suffix,hash_value):
    connection = Connection()
    cursor = connection.cursor()
    cursor.execute("select * from dba_users u where u.USERNAME like '{}'".format(username))
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    cursor.close()
    connection.close()

user_suffix="Hello"
hash_value="12345"
test_target(user_suffix,hash_value)

1 Ответ

0 голосов
/ 07 августа 2020

Я внес изменения в test.py. Вы можете извлечь из соединения любую запись, например имя пользователя, dsn. В классе подключения есть и другие функции

from connection import *    
from sample import *

def test_target(user_suffix,hash_value):
    connection = Connection()
    cursor = connection.cursor()
    username = connection.username
    cursor.execute("select * from dba_users u where u.USERNAME like '{}'".format(username))
    rows = cursor.fetchall()
    for row in rows:
        print(row)
    cursor.close()
    connection.close()

user_suffix="Hello"
hash_value="12345"
test_target(user_suffix,hash_value)
...