python project directory structure

Item 1

README

It needs to explain the following:

  1. Software positioning, basic functions of software.
  2. Method of running code: installation environment, startup command, etc.
  3. Brief instructions for use.
  4. Description of code directory structure, which can explain the basic principle of software in more detail.
  5. Description of frequently asked questions.

setup.py

Generally speaking, setup.py is used to manage the packaging, installation and deployment of code. The industry standard is to use setuptools, a popular Python packaging tool, to manage these things.
This approach is widely used in open source projects. However, the core idea here is not to use standardized tools to solve these problems, but that a project must have an installation and deployment tool,
It can quickly and conveniently install the environment, deploy the code and run the program on a new machine.
setup.py can automate these things, improve efficiency and reduce the probability of errors. "Complex things are automated, and things that can be automated must be automated." is a very good habit.
The documentation of setuptools is relatively large. It may not be easy to find the entry point when you first contact it. The way to learn technology is to see how others use it. You can refer to a Web framework of Python,
How flash is written: setup.py of course, it's easy to write an installation script (deploy.sh) instead of setup.py.

requirements.txt

The purpose of this file is:

It is convenient for developers to maintain software package dependencies. Add the package added in the development process to this list to avoid missing the software package when installing the dependency of setup.py. It is convenient for readers to know which Python packages are used in the project.
The format of this file is that each line contains a description of package dependencies, usually in the format of flash > = 0.10. It is required that this format can be recognized by pip, so that all Python package dependencies can be installed simply through pip install -r requirements.txt. Requirements files

code

#=============>Bin directory: store execution scripts
#start.py
import sys,os

BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from core import core
from conf import my_log_settings

if __name__ == '__main__':
    my_log_settings.load_my_logging_cfg()
    core.run()

#=============>Conf Directory: stores configuration files
#config.ini
[DEFAULT]
user_timeout = 1000

[x]
password = 123
money = 10000000

[y]
password = 123456
money=1000

[z]
password = qwe123
money=10

#settings.py
import os
config_path=r'%s\%s' %(os.path.dirname(os.path.abspath(__file__)),'config.ini')
user_timeout=10
user_db_path=r'%s\%s' %(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),\
                     'db')


#my_log_settings.py
"""
logging to configure
"""

import os
import logging.config

# Start by defining three log output formats

standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
                  '[%(levelname)s][%(message)s]' #Where name is the name specified by getlogger

simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'

id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'

# End of defining log output format

logfile_dir = r'%s\log' %os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # Directory of the log file

logfile_name = 'all2.log'  # log file name

# If there is no defined log directory, create one
if not os.path.isdir(logfile_dir):
    os.mkdir(logfile_dir)

# Full path of log file
logfile_path = os.path.join(logfile_dir, logfile_name)

# log configuration dictionary
LOGGING_DIC = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'standard': {
            'format': standard_format
        },
        'simple': {
            'format': simple_format
        },
    },
    'filters': {},
    'handlers': {
        #Log printed to terminal
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',  # Print to screen
            'formatter': 'simple'
        },
        #Print logs to files and collect logs of info and above
        'default': {
            'level': 'DEBUG',
            'class': 'logging.handlers.RotatingFileHandler',  # Save to file
            'formatter': 'standard',
            'filename': logfile_path,  # log file
            'maxBytes': 1024*1024*5,  # Log size 5M
            'backupCount': 5,
            'encoding': 'utf-8',  # The coding of log files, no longer have to worry about Chinese log garbled
        },
    },
    'loggers': {
        #logger configuration obtained from logging.getlogger (_name_)
        '': {
            'handlers': ['default', 'console'],  # Here, both handler s defined above are added, that is, log data is written to the file and printed to the screen
            'level': 'DEBUG',
            'propagate': True,  # Pass up (higher level logger)
        },
    },
}


def load_my_logging_cfg():
    logging.config.dictConfig(LOGGING_DIC)  # Import the logging configuration defined above
    logger = logging.getLogger(__name__)  # Generate a log instance
    logger.info('It works!')  # Record the operation status of the file

if __name__ == '__main__':
    load_my_logging_cfg()

#=============>Core Directory: stores core logic
#core.py
import logging
import time
from conf import settings
from lib import read_ini
from conf import my_log_settings

# print(__name__)
config = read_ini.read(settings.config_path)
logger = my_log_settings.load_my_logging_cfg(__name__)

current_user={'user':None,'login_time':None,'timeout':int(settings.user_timeout)}
def auth(func):
    def wrapper(*args,**kwargs):
        if current_user['user']:
            interval=time.time()-current_user['login_time']
            if interval < current_user['timeout']:
                return func(*args,**kwargs)
        name = input('name>>: ')
        password = input('password>>: ')
        if config.has_section(name):
            if password == config.get(name,'password'):
                logger.info('Login succeeded')
                current_user['user']=name
                current_user['login_time']=time.time()
                return func(*args,**kwargs)
            else:
                logger.error('Login failed')
        else:
            logger.error('user name does not exist')

    return wrapper

@auth
def buy():
    print('buy...')

@auth
def run():

    print('''
shopping
 View balance
 transfer accounts
    ''')
    while True:
        choice = input('>>: ').strip()
        if not choice:continue
        if choice == '1':
            buy()

#=============>DB Directory: store database files
#x_json
#y_json

#=============>Lib Directory: stores customized modules and packages
#read_ini.py
import configparser
def read(config_file):
    config=configparser.ConfigParser()
    config.read(config_file)
    return config

#=============>Log directory: store logs
#all.log
[2018-04-20 00:19:48,587][MainThread:10840][task_id:__main__][my_logsettiing.py:75][INFO][It works!]
[2018-04-20 00:28:29,387][MainThread:9492][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:32:14,803][MainThread:15240][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:39:30,564][MainThread:11216][task_id:__main__][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:39:46,132][MainThread:11216][task_id:__main__][core.py:22][INFO][Login succeeded]
[2018-04-20 00:41:27,929][MainThread:6644][task_id:core.core][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:41:44,162][MainThread:8620][task_id:core.core][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:41:44,163][MainThread:8620][task_id:__main__][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:41:53,689][MainThread:8620][task_id:core.core][core.py:29][ERROR][user name does not exist]
[2018-04-20 00:44:33,641][MainThread:14012][task_id:__main__][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:44:42,086][MainThread:14012][task_id:__main__][core.py:22][INFO][Login succeeded]
[2018-04-20 00:47:22,321][MainThread:9460][task_id:__main__][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:47:25,847][MainThread:9460][task_id:__main__][core.py:29][ERROR][user name does not exist]
[2018-04-20 00:51:58,265][MainThread:14784][task_id:core.core][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:51:58,265][MainThread:14784][task_id:__main__][my_log_settings.py:75][INFO][It works!]
[2018-04-20 00:52:14,703][MainThread:14784][task_id:core.core][core.py:22][INFO][Login succeeded]

Item 2

  1. bin directory: it is the directory of the execution file of the entire application, and the start.py file is the startup entry
  2. conf Directory: it is the configuration file directory of the entire application, and config.yaml is one of the configuration files
  3. Core Directory: it is the core module of the whole application, and core.py is the core business logic script file
  4. db Directory: it is the database file directory of the whole application
  5. lib Directory: it is the storage directory for general function scripts and third-party application files of the whole application
  6. Log directory: it is the directory of log files for the entire application
  7. res Directory: it is the directory of icons, pictures, ui, etc. of the entire application
  8. tests Directory: it is the directory of test files for the entire application
  9. Venv Win32 Directory: it is the 32-bit virtual environment directory of the entire application, which is used to run and package 32-bit applications
  10. venv-win64 Directory: it is the 64 bit virtual environment directory of the entire application, which is used to run and package 64 applications
  11. readme.txt: project description document
  12. requirements.txt: used to store the list of external Python packages that the entire application depends on

Item 3


ProjectName

Keywords: Python Flask

Added by pvechi on Tue, 28 Sep 2021 08:44:01 +0300