TypeError: ‘NoneType’ object does not support the context manager protocol

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import os
import json
import platform
import logging
import pymysql as pm
import boto3
from botocore.exceptions import ClientError
import logging
class LogOutput:
env=None
config=None
def __init__(self, env_filename):
self.env=env_filename
self.config=self.get_config()
def get_config(self):
with open(self.env) as file_in:
return json.load(file_in)
def is_Windows():
if "win" in (platform.system().lower()):
return True
else:
return False
def DB_connection(self):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
connection = None
try:
config=LogOutput.get_config(self)
host=config["DB_conn_info_local"]["database-secrets"]["host"]
port=config["DB_conn_info_local"]["database-secrets"]["port"]
database=config["DB_conn_info_local"]["database-secrets"]["db"]
username=config["DB_conn_info_local"]["database-secrets"]["username"]
password=config["DB_conn_info_local"]["database-secrets"]["password"]
# Load the configuration from DB_conn_info_local.json
config_file_path = os.path.join(os.path.dirname(__file__), 'DB_conn_info_local.json')
with open(config_file_path) as config_file:
config = json.load(config_file)
connection = pm.connect(user=username,password=password,host=host,port=port,database=database)
logger.info("Successfully connected to database")
except Exception as e:
logger.error("Unable to connect to database: %s", str(e))
return connection
def logging_sp(self):
logging_sp_query = """
stored procedure query here
"""
with self.DB_connection() as cnxn:
with cnxn.cursor() as cur:
try:
cur.execute(logging_sp_query)
except Exception as e:
logging.exception(e)
else:
cnxn.commit()
def main():
cwd=os.getcwd()
if "win" in (platform.system().lower()):
vfc=(cwd+"\DB_conn_info_local"+".json")
else:
vfc=(cwd+"/DB_conn_info_local"+".json")
ve=LogOutput(vfc)
ve.logging_sp()
if __name__ == "__main__":
main()
</code>
<code>import os import json import platform import logging import pymysql as pm import boto3 from botocore.exceptions import ClientError import logging class LogOutput: env=None config=None def __init__(self, env_filename): self.env=env_filename self.config=self.get_config() def get_config(self): with open(self.env) as file_in: return json.load(file_in) def is_Windows(): if "win" in (platform.system().lower()): return True else: return False def DB_connection(self): logger = logging.getLogger() logger.setLevel(logging.INFO) connection = None try: config=LogOutput.get_config(self) host=config["DB_conn_info_local"]["database-secrets"]["host"] port=config["DB_conn_info_local"]["database-secrets"]["port"] database=config["DB_conn_info_local"]["database-secrets"]["db"] username=config["DB_conn_info_local"]["database-secrets"]["username"] password=config["DB_conn_info_local"]["database-secrets"]["password"] # Load the configuration from DB_conn_info_local.json config_file_path = os.path.join(os.path.dirname(__file__), 'DB_conn_info_local.json') with open(config_file_path) as config_file: config = json.load(config_file) connection = pm.connect(user=username,password=password,host=host,port=port,database=database) logger.info("Successfully connected to database") except Exception as e: logger.error("Unable to connect to database: %s", str(e)) return connection def logging_sp(self): logging_sp_query = """ stored procedure query here """ with self.DB_connection() as cnxn: with cnxn.cursor() as cur: try: cur.execute(logging_sp_query) except Exception as e: logging.exception(e) else: cnxn.commit() def main(): cwd=os.getcwd() if "win" in (platform.system().lower()): vfc=(cwd+"\DB_conn_info_local"+".json") else: vfc=(cwd+"/DB_conn_info_local"+".json") ve=LogOutput(vfc) ve.logging_sp() if __name__ == "__main__": main() </code>
import os 
import json
import platform
import logging
import pymysql as pm
import boto3
from botocore.exceptions import ClientError
import logging


class LogOutput:
    env=None
    config=None
    

    def __init__(self, env_filename):
        self.env=env_filename
        self.config=self.get_config()

    def get_config(self):
        with open(self.env) as file_in:
            return json.load(file_in)
        
    def is_Windows():
        if "win" in (platform.system().lower()):
            return True
        else:
            return False        

    def DB_connection(self):
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        connection = None
        try:
            config=LogOutput.get_config(self)
            host=config["DB_conn_info_local"]["database-secrets"]["host"]
            port=config["DB_conn_info_local"]["database-secrets"]["port"]
            database=config["DB_conn_info_local"]["database-secrets"]["db"]
            username=config["DB_conn_info_local"]["database-secrets"]["username"]
            password=config["DB_conn_info_local"]["database-secrets"]["password"]

            # Load the configuration from DB_conn_info_local.json
            config_file_path = os.path.join(os.path.dirname(__file__), 'DB_conn_info_local.json')
            with open(config_file_path) as config_file:
                config = json.load(config_file)

            connection = pm.connect(user=username,password=password,host=host,port=port,database=database)
    
            logger.info("Successfully connected to database")

        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))
        
        return connection
    
    def logging_sp(self):
        logging_sp_query = """

        stored procedure query here 
     
        """
        with self.DB_connection() as cnxn:
            with cnxn.cursor() as cur:
                try:
                    cur.execute(logging_sp_query)

                except Exception as e:
                        logging.exception(e)

                else:
                    cnxn.commit()
   

def main():
    cwd=os.getcwd()
    if "win" in (platform.system().lower()):
        vfc=(cwd+"\DB_conn_info_local"+".json")
    else:
        vfc=(cwd+"/DB_conn_info_local"+".json")
    ve=LogOutput(vfc)
    ve.logging_sp()
   
if __name__ == "__main__":
    main()

I keep getting this error:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code> with self.DB_connection() as cnxn:
TypeError: 'NoneType' object does not support the context manager protocol
</code>
<code> with self.DB_connection() as cnxn: TypeError: 'NoneType' object does not support the context manager protocol </code>
    with self.DB_connection() as cnxn:
TypeError: 'NoneType' object does not support the context manager protocol

Is it because I am using “with”? Is there another way to execute it? It uses a json config file that it reads which contains the credentials. I didn’t need to include that here. I saw other posts saying “with” return none so that’s why it’s executing basically nothing? I don’t know how to re-write this because I am using with twice.

2

Ensure DB_connection() returns a valid connection:

Your DB_connection() method should return the connection object from pymysql when successful.
In case of an error, ensure that you either raise an exception or handle the None value appropriately.
Check for None in logging_sp():

Before proceeding with with self.DB_connection(), you should verify that the connection object (cnxn) is not None.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import os
import json
import platform
import pymysql as pm
import boto3
from botocore.exceptions import ClientError
import logging
class LogOutput:
env = None
config = None
def __init__(self, env_filename):
self.env = env_filename
self.config = self.get_config()
def get_config(self):
with open(self.env) as file_in:
return json.load(file_in)
def is_Windows():
return "win" in platform.system().lower()
def DB_connection(self):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
connection = None
try:
config = self.config
host = config["DB_conn_info_local"]["database-secrets"]["host"]
port = config["DB_conn_info_local"]["database-secrets"]["port"]
database = config["DB_conn_info_local"]["database-secrets"]["db"]
username = config["DB_conn_info_local"]["database-secrets"]["username"]
password = config["DB_conn_info_local"]["database-secrets"]["password"]
# Establish the connection
connection = pm.connect(user=username, password=password, host=host, port=port, database=database)
logger.info("Successfully connected to database")
except Exception as e:
logger.error("Unable to connect to database: %s", str(e))
return connection
def logging_sp(self):
logging_sp_query = """
stored procedure query here
"""
cnxn = self.DB_connection()
if cnxn is None:
logging.error("Database connection is None. Cannot proceed.")
return # we exit here if there's no valid connection
with cnxn.cursor() as cur:
try:
cur.execute(logging_sp_query)
except Exception as e:
logging.exception(e)
else:
cnxn.commit()
cnxn.close() # we have to close the connection afterwards
def main():
cwd = os.getcwd()
if "win" in platform.system().lower():
vfc = os.path.join(cwd, "DB_conn_info_local.json")
else:
vfc = os.path.join(cwd, "DB_conn_info_local.json")
ve = LogOutput(vfc)
ve.logging_sp()
if __name__ == "__main__":
main()
</code>
<code>import os import json import platform import pymysql as pm import boto3 from botocore.exceptions import ClientError import logging class LogOutput: env = None config = None def __init__(self, env_filename): self.env = env_filename self.config = self.get_config() def get_config(self): with open(self.env) as file_in: return json.load(file_in) def is_Windows(): return "win" in platform.system().lower() def DB_connection(self): logger = logging.getLogger() logger.setLevel(logging.INFO) connection = None try: config = self.config host = config["DB_conn_info_local"]["database-secrets"]["host"] port = config["DB_conn_info_local"]["database-secrets"]["port"] database = config["DB_conn_info_local"]["database-secrets"]["db"] username = config["DB_conn_info_local"]["database-secrets"]["username"] password = config["DB_conn_info_local"]["database-secrets"]["password"] # Establish the connection connection = pm.connect(user=username, password=password, host=host, port=port, database=database) logger.info("Successfully connected to database") except Exception as e: logger.error("Unable to connect to database: %s", str(e)) return connection def logging_sp(self): logging_sp_query = """ stored procedure query here """ cnxn = self.DB_connection() if cnxn is None: logging.error("Database connection is None. Cannot proceed.") return # we exit here if there's no valid connection with cnxn.cursor() as cur: try: cur.execute(logging_sp_query) except Exception as e: logging.exception(e) else: cnxn.commit() cnxn.close() # we have to close the connection afterwards def main(): cwd = os.getcwd() if "win" in platform.system().lower(): vfc = os.path.join(cwd, "DB_conn_info_local.json") else: vfc = os.path.join(cwd, "DB_conn_info_local.json") ve = LogOutput(vfc) ve.logging_sp() if __name__ == "__main__": main() </code>
import os 
import json
import platform
import pymysql as pm
import boto3
from botocore.exceptions import ClientError
import logging

class LogOutput:
    env = None
    config = None
    

    def __init__(self, env_filename):
        self.env = env_filename
        self.config = self.get_config()

    def get_config(self):
        with open(self.env) as file_in:
            return json.load(file_in)
        
    def is_Windows():
        return "win" in platform.system().lower()

    def DB_connection(self):
        logger = logging.getLogger()
        logger.setLevel(logging.INFO)
        connection = None
        try:
            config = self.config

            host = config["DB_conn_info_local"]["database-secrets"]["host"]
            port = config["DB_conn_info_local"]["database-secrets"]["port"]
            database = config["DB_conn_info_local"]["database-secrets"]["db"]
            username = config["DB_conn_info_local"]["database-secrets"]["username"]
            password = config["DB_conn_info_local"]["database-secrets"]["password"]

            # Establish the connection
            connection = pm.connect(user=username, password=password, host=host, port=port, database=database)
            logger.info("Successfully connected to database")

        except Exception as e:
            logger.error("Unable to connect to database: %s", str(e))
        
        return connection
    
    def logging_sp(self):
        logging_sp_query = """
        stored procedure query here
        """
        
        cnxn = self.DB_connection()
        if cnxn is None:
            logging.error("Database connection is None. Cannot proceed.")
            return  # we exit here if there's no valid connection
            
        with cnxn.cursor() as cur:
            try:
                cur.execute(logging_sp_query)
            except Exception as e:
                logging.exception(e)
            else:
                cnxn.commit()
        cnxn.close()  # we have to close the connection afterwards

def main():
    cwd = os.getcwd()
    if "win" in platform.system().lower():
        vfc = os.path.join(cwd, "DB_conn_info_local.json")
    else:
        vfc = os.path.join(cwd, "DB_conn_info_local.json")
    
    ve = LogOutput(vfc)
    ve.logging_sp()
   
if __name__ == "__main__":
    main()

8

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật