Python 简单后台项目的脚手架

说明

近期写了一个简单的项目,在后台运行获取网上的期货数据并保存到相应的数据库里。由于之前工作很多这种简单的类似调用接口或攫取数据的项目都是用 Python 来写,因此这次也继续用 Python 写。但是这次更换了几个包,此份文档简单来说明一下。

依赖的包

  • toml: 用户解析配置文件,配置文件用的是 toml 格式。
  • arrow: 用于处理日期相关。
  • loguru: 用于日志处理。
  • requests: 用于 http 请求响应。
  • pandas: 用于数据处理。
  • numpy: 用于数据计算。
  • mysql-connector-python: 用于操作 MySQL 数据库。
  • SQLAlchemy: 用于操作数据库。
  • click: 用于命令行参数解析。

项目结构

$ tree -L 2
.
├── README.md
├── config
│   └── config.toml.                            # 配置文件
├── log                                         # 日志目录
├── app_demo                                    # 程序目录
│   ├── __init__.py
│   ├── config.py                               # 加载配置信息代码
│   ├── container.py.                           # 容器类
│   ├── exceptions.py                           # 异常类
│   ├── log.py                                  # 日志程序
│   └── main.py                                 # 主程序
├── setup.py                                    # 安装程序
└── venv                                        # 虚拟环境
    ├── bin
    ├── lib
    └── pyvenv.cfg


部分代码示例

1、main.py

import time  
import arrow  
import numpy as np  
import click  
import sqlalchemy  
from sqlalchemy import text  
from app_demp.container import Container  
  
config = None  
log = None  
db = None  
  
@click.command()  
@click.option('--config_file', default='./config.toml', help='Specify config file')  
@click.option('--start_date', default=None, help='Specify start date')  
@click.option('--end_date', default=None, help='Specify end date')  
def main(config_file, start_date, end_date):  
    global config, log, db
    print("Load config file: {}".format(config_file))  
    container = Container(config_file)  
    config = container.get_config()  
    log = container.get_logger()  
    log.info("Load config file: {}".format(config_file))  
    db = container.get_db()  
  
    if start_date is None or end_date is None:  
        start_date = arrow.now().format('YYYYMMDD')  
        end_date = start_date  
  
    log.info("Date Info, start date: {}, end date: {}".format(start_date, end_date))  
  
    run(start_date, end_date)  


if __name__ == '__main__':  
    main()


2、container.py

from sqlalchemy import create_engine  
from sqlalchemy.orm import sessionmaker  
  
  
class Container(object):  
    """  
    容器类  
    """  
    def __init__(self, config_file):  
        """  
  
        """        self.config_file = config_file  
        self.config = None  
        self.logger = None  
        self.db = None  
  
    def get_config(self):  
        """  
        获取指定配置信息  
        :return:  
        """        if self.config is None:  
            from app_demo.config import get_config  
            self.config = get_config(self.config_file)  
        return self.config  
  
    def get_logger(self):  
        """  
        获取日志对象  
        :return:  
        """  
        if self.config is None:  
            self.get_config()  
        if self.logger is None:  
            from app_demo.log import get_logger  
            self.logger = get_logger(self)  
        return self.logger  
  
    def get_db(self):  
        if self.config is None:  
            self.get_config()  
  
        if self.db is None:  
            dsn = "mysql+mysqlconnector://{user}:{password}@{host}:{port}/{database}?auth_plugin=mysql_native_password".format(  
                    user=self.get_config().get('db').get('user'),  
                    password=self.get_config().get('db').get('password'),  
                    host=self.get_config().get('db').get('host'),  
                    port=self.get_config().get('db').get('port'),  
                    database=self.get_config().get('db').get('database'),  
                )  
  
            engine = create_engine(dsn, echo=False)  
            db_session = sessionmaker(bind=engine, autoflush=True, expire_on_commit=True)  
            self.db = db_session()  
  
        return self.db

3、config.py

import toml  
  
from app_demo.exceptions import *  
  
  
def get_config(config_file):  
    if config_file is not None:  
        with open(config_file) as config_file_handler:  
            config = toml.loads(config_file_handler.read())  
  
            if not all(key in config for key in ['log']):  
                raise ConfigException('Config error, config file: {file}'.format(file=config_file))  
  
            if not (isinstance(config.get('db'), dict) and all(key in config.get('db') for key in  
                                                               ['host', 'port', 'database', 'user', 'password'])):  
                raise ConfigException('Config error, config file: {file}'.format(file=config_file))  
        return config  
    else:  
        raise Exception('Can not retrieve config file')

4、log.py

from loguru import logger  
  
  
def get_logger(container):  
    log_config = container.get_config().get('log')  
  
    logger.add(  
        log_config.get('filename'),  
        rotation=log_config.get('rotation_size'),  
        retention=log_config.get('retention'),  
        compression=log_config.get('compression'),  
    )  
  
    return logger

以上就是“Python 简单后台项目的脚手架”的全部内容,希望对你有所帮助。

关于Python技术储备

学好 Python 不论是就业还是做副业赚钱都不错,但要学会 Python 还是要有一个学习规划。最后大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

一、Python所有方向的学习路线

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

在这里插入图片描述

二、Python必备开发工具

img

三、Python视频合集

观看零基础学习视频,看视频学习是最快捷也是最有效果的方式,跟着视频中老师的思路,从基础到深入,还是很容易入门的。

img

四、实战案例

光学理论是没用的,要学会跟着一起敲,要动手实操,才能将自己的所学运用到实际当中去,这时候可以搞点实战案例来学习。

img

五、Python练习题

检查学习结果。

img

六、面试资料

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

img

最后祝大家天天进步!!

上面这份完整版的Python全套学习资料已经上传至CSDN官方,朋友如果需要可以直接微信扫描下方CSDN官方认证二维码免费领取【保证100%免费】。

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值