References and import log bundle

1. The use of the package

  • import

    • First class: the implementation of the file used to import the package and the package import function

      • Aaa create a package, create a self- __innt__py file

      • Create a module tbjx three things happen:

        • The file is loaded into memory tbjx
        • Create a namespace name to tbjx
        • By tbjx. Tbjx of reference of the names of all modules
      • Create a package of three things will happen:

        • Aaa within the package __init__py file is loaded into memory

        • Aaa name to create a namespace

        • By aaa. Of reference __init__of the names of all

          import aaa
          # print(aaa.x)
          # aaa.f1()
          # print(aaa.m1)
          # print(aaa.m1.a)
          # 我想要引用 aaa包的m1文件的a变量
          # 错误示例1:
          import aaa
          # 1. aaa的 __init__ 里面 写import m1
          # 2. print(aaa.m1.a)
          # print(aaa.m1.a)
          # 报错原因: No module named 'm1'
          # 分析报错原因: 模块找不到 内存,内置,sys.path三个地方找不到.
          # m1 不在内存,不在内置,sys.path 会主动加载执行文件(包的使用.py)的当前目录.
          # 解决方式:
          import aaa
          # 1. 在执行文件写入 import aaa
          # 2. aaa的 __init__ 里面 写 from aaa import m1
          # 3. 然后在执行文件  aaa.m1.a
          # print(aaa.m1.a)
          # aaa.m1.func1()
          import aaa
          # 如何在当前文件中,引用 aaa包的bbb包.
          # 1. 在执行文件写入 import aaa
          # 2. aaa的 __init__ 里面 写 from aaa import bbb
          # 3. 然后在执行文件  aaa.bbb
          # print(aaa.bbb)
          # 如何在当前文件中,引用 aaa包的bbb包 的 变量 name.
          # 1. 在执行文件写入 import aaa
          # 2. aaa的 __init__ 里面 写 from aaa import bbb
          # 3. 然后在执行文件  aaa.bbb
          # print(aaa.bbb)
          import aaa
          # print(aaa.bbb.name)
          # 如何在当前文件中,引用 aaa包的bbb包 的 mb文件的函数func.
          # 1. 在执行文件写入 import aaa
          # 2. 在aaa包的__Init__ 写上 from aaa import bbb  (这样写 bbb包的__init__里面所有的名字都能引用)
          # print(aaa.bbb.name)
          # 3. 在bbb包的__Init__ 写上 from aaa.bbb import mb
          # aaa.bbb.mb.func3()
          # 首先 无论从哪里引用模块,import 或者 from  ... import ...
          # 最开始的模块或者包名一定是内存,内置,sys.path中能找到的.(可参考bbb包中的 __init__)
          # 直接import 为了让我们会使用 包里面的 __init__
  • from ... import ...

    # from ... import ...
    # 通过这种方式不用设置__init__文件
    # from aaa import m1
    # m1.func()
    # from aaa.bbb.m2 import func1
    # func1()
    # from aaa.bbb import m2
    # m2.func1()
    # from a.b.c import d.e.f
    # c的. 的前面一定是包
    # import 的后面一定是名字,并且不能 再有点
    # from aaa.bbb.m2.func1 import a  # 错误的
    # from aaa.bbb import m2
    # m2.func1()

2. Log

  • low version Log

    • # import logging
      # logging.basicConfig(
      #     level=logging.DEBUG,
      # )
      # # logging.debug('debug message')
      # # logging.info('info message')
      # # logging.warning('warning message')
      # # logging.error('error message')
      # # logging.critical('critical message')
      # 应用:
      # def func():
      #     print('in func')
      #     logging.debug('正常执行')
      # func()
      # try:
      #     i = input('请输入选项:')
      #     int(i)
      # except Exception as e:
      #     logging.error(e)
      # print(11)
      # low版的日志:缺点: 文件与屏幕输入只能选择一个.
      import logging
      logging.basicConfig(
          # level=logging.DEBUG,
          level=30,
          format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
          filename=r'test.log',
      )
      # logging.debug('调试模式')  # 10
      # logging.info('正常模式')  # 20
      logging.warning('警告信息')  # 30
      # logging.error('错误信息')  # 40
      # logging.critical('严重错误信息')  # 50
  • Standard Edition log

    • # import logging
      # # 创建一个logging对象
      # logger = logging.getLogger()
      # # 创建一个文件对象
      # fh = logging.FileHandler('标配版.log', encoding='utf-8')
      # # 创建一个屏幕对象
      # sh = logging.StreamHandler()
      # # 配置显示格式
      # formatter1 = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
      # formatter2 = logging.Formatter('%(asctime)s %(message)s')
      # fh.setFormatter(formatter1)
      # sh.setFormatter(formatter2)
      # logger.addHandler(fh)
      # logger.addHandler(sh)
      # # 总开关
      # logger.setLevel(10)
      # fh.setLevel(10)
      # sh.setLevel(40)
      # logging.debug('调试模式')  # 10
      # logging.info('正常模式')  # 20
      # logging.warning('警告信息')  # 30
      # logging.error('错误信息')  # 40
      # logging.critical('严重错误信息')  # 50
  • Ultimate log

    • """
      logging配置
      """
      import logging.config
      # 定义三种日志输出格式 开始
      standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                        '[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字
      simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
      id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
      # 定义日志输出格式 结束
      logfile_name = 'login.log'  # log文件名
      logfile_path_staff = r'D:\s23\day19\日志模块\旗舰版日志文件夹\staff.log'
      logfile_path_boss = r'D:\s23\day19\日志模块\旗舰版日志文件夹\boss.log'
      # log配置字典
      # LOGGING_DIC第一层的所有的键不能改变
      LOGGING_DIC = {
          'version': 1,  # 版本号
          'disable_existing_loggers': False,  # 固定写法
          'formatters': {
              'standard': {
                  'format': standard_format
              },
              'simple': {
                  'format': simple_format
              },
              'id_simple':{
                  'format': id_simple_format
              }
          },
          'filters': {},
          'handlers': {
              #打印到终端的日志
              'sh': {
                  'level': 'DEBUG',
                  'class': 'logging.StreamHandler',  # 打印到屏幕
                  'formatter': 'id_simple'
              },
              #打印到文件的日志,收集info及以上的日志
              'fh': {
                  'level': 'DEBUG',
                  'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                  'formatter': 'standard',
                  'filename': logfile_path_staff,  # 日志文件
                  'maxBytes': 5000,  # 日志大小 5M
                  'backupCount': 5,
                  'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
              },
              'boss':
                  {
                      'level': 'DEBUG',
                      'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
                      'formatter': 'id_simple',
                      'filename': logfile_path_boss,  # 日志文件
                      'maxBytes': 5000,  # 日志大小 5M
                      'backupCount': 5,
                      'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
                  },
          },
          'loggers': {
              #logging.getLogger(__name__)拿到的logger配置
              '': {
                  'handlers': ['sh', 'fh', 'boss'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
                  'level': 'DEBUG',
                  'propagate': True,  # 向上(更高level的logger)传递
              },
          },
      }
      def md_logger():
          logging.config.dictConfig(LOGGING_DIC)  # 导入上面定义的logging配置
          logger = logging.getLogger()  # 生成一个log实例
          return logger
          # logger.debug('It works!')  # 记录该文件的运行状态
      dic = {
          'username': '小黑'
      }
      def login():
          # print('登陆成功')
          md_logger().info(f"{dic['username']}登陆成功")
      # def aricle():
      #     print('欢迎访问文章页面')
      login()
      # aricle()

3. The reference to cross-module package

  • As more and more of your module file, you need to divide the module file, such as the interaction with the database are responsible for putting a folder to put the relevant page of interacting with a folder,

    my_proj/
    ├── apeland_web  #代码目录
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py
    └── my_proj    #配置文件目录    
      ├── __init__.py    
        ├── settings.py    
        ├── urls.py    
        └── wsgi.py

    Like above, a plurality of folder management module files, the folder is called packet

    A package is a folder, but the folder must exist under the init .py file, the contents of the file can be empty, int .py the current folder is used to identify a package.

    This the init .py file is mainly used to package some initialization, and when this package is currently being called by another program, the init .py file will be executed first, usually empty, some of you want to be called as long as the package is executed immediately the code can be placed in the init .py, the back will be a demonstration.

    Cross-module import

    Directory structure is as follows

    my_proj
    ├── apeland_web
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   └── views.py
    ├── manage.py
    └── my_proj    
      ├── settings.py    
        ├── urls.py    
        └── wsgi.py

    According to the above structure, how to achieve apeland import my web / views.py inproj/settings.py module?

    Directly into the case, it will complain that module not found

    img

    Because the path is not found, my_proj / settings.py equivalent? Apeland_web / views.py father (apeland_web) brother (my_proj) son (settings.py), settings.py regarded cousin views.py friends, in views.py can only import the same level in the code module brothers, or sublevels bag module, we do not know exist cousin cousin. what should I do?

    The answer is to add environment variables, adding the path to sys.path father class, you can, so to import the equivalent grade from father to start looking for a module.

    apeland_web / views.py add environment variables

    import sys ,osBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #__file__的是打印当前被执行的模块.py文件相对路径,注意是相对路径print(BASE_DIR) # 输出是/Users/alex/PycharmProjects/apeland_py_learn/day4_常用模块/my_proj sys.path.append(BASE_DIR)from  my_proj import settingsprint(settings.DATABASES)

    Cross-official recommended import method

    Although you can import cross-module by adding an environment variable way, but officials do not recommend doing so, because it will need to write again to add the code environment variables in each program under each directory.

    The official recommended play is to create a program entry in the project, the whole process should be initiated by calling the start of the program from the entrance, the entrance procedure is generally placed in the top-level directory of the project

    The advantage of this is that the project level two apeland_web / views.py in recalling his cousin my_proj / will not need to add environment variables when settings.py.

    The reason is because manage.py on the top floor, the environment variable path manage.py start of the project will automatically become ... .xxx / my_proj / at this level

    img

Guess you like

Origin www.cnblogs.com/W-Y-C/p/11116460.html