python代码规范

代码基本规范:

  • 代码风格的规范,需要符合PEP8规范。范例:

#!/user/bin/env python3
# -*- coding: utf-8 -*-
#
# 此文件包含“框架代码”,请确保已获得本公司的许可。
#
# Copyright (c) 2021, 上海掌签信息科技有限公司. 保留所有权.
#
import argparse
import os
import shutil

import yaml2rst


def parse_args() -> None:
"""
获取启动程序时的命令行参数。
"""
    parser = argparse.ArgumentParser()
    parser.add_argument('--configs_path',
                        help="Please enter config, example:CONFIGSDIR")

    args = parser.parse_args()
    return args


def schema2rst() -> None:
    configs_path = parse_args().configs_path
    if configs_path is None:
        configs_path = "configs"
    source_config_path = os.path.join(os.getcwd(), "source")
    rst_config_path = os.path.join(source_config_path, configs_path)

    if os.path.exists(rst_config_path):
        shutil.rmtree(rst_config_path)
        os.mkdir(rst_config_path)
    else:
        os.mkdir(rst_config_path)

    configs_path = os.path.join(os.path.dirname(os.path.dirname((os.path.abspath(__file__)))), 'configs')
    base_path = os.path.join(configs_path, 'base')

    for schema in os.listdir(base_path):
        if schema.split('.')[-1] == 'schema':
            schema_name = f"{schema.split('.')[0]}_schema"
            rst_name = f"{schema_name}.rst"
            yaml2rst.convert_file(os.path.join(base_path, schema), os.path.join(rst_config_path, rst_name))

if __name__ == '__main__':
    schema2rst()
  • 配置文件规范:公司推荐使用yaml和ini文件格式做为配置文件格式,如下:

flak8:
    title:palmsion

pylint:
    time:night

版本规范:

  • 安装包的规范,只能使用公司规定的第三方包。

  • 公司规定只能采用python3.8.8版本的python版本。

  • 只能使用公司规定的第三方包和对应的版本。超出范围的需要邮件申请,邮箱地址为xeky@163.com 申请时写明原因。

flask项目目录结构要求:

  • 公司对项目目录结构有一定的要求,需要遵照以下要求:

../_images/flask-tp.png
  • 只有在上述目录结构不能囊括的情况才可以添加相应的目录。比如需要写一个相对独立的工具模块,就可以自行添加一个tools目录。

  • 解析请求须采用RequestParser()方法,因为自动化生成单元测试用例需要解析此处的校验参数。返回参数只能是封装好的api_result(),返回值只有3个key:data, status_code, message。

  • 一个符合标准的接口应该是如下形式的:

class AddInterfaceApi(Resource):
    # method_decorators = [jwt_required()]
    def post(self):
        # username = get_jwt_identity()
        parser = RequestParser()
        parser.add_argument('name', type=str, required=True, nullable=False,location='json')  # 记录route
        parser.add_argument('route', type=str, required=True, nullable=False, location='json')  # 记录route
        parser.add_argument('rule', type=str, required=True,  location='json')
        parser.add_argument('method', type=str, location='json')
        args = parser.parse_args()
        interface = InterFace(id=rand_id(), name=args["name"], route=args["route"], rule=args["rule"],
                              method=args["method"])
        db.session.add(interface)
        db.session.commit()
        return jsonify(api_result("添加接口成功"))

公司可用的包清单:可以直接复制到虚拟环境:

alabaster==0.7.12
alembic==1.4.2
aliyun-python-sdk-core-v3==2.13.11
aliyun-python-sdk-kms==2.11.0
aliyun-python-sdk-rds==2.5.1
aniso8601==8.0.0
anyio==3.4.0
APScheduler==3.6.3
attrs==21.2.0
azt==0.0.7
Babel==2.8.0
beautifulsoup4==4.10.0
blinker==1.4
bs4==0.0.1
certifi==2020.6.20
cffi==1.14.2
chardet==3.0.4
charset-normalizer==2.0.10
click==8.0.3
cloud-init==19.1.9
colorama==0.4.4
command-not-found==0.3
configobj==5.0.6
crcmod==1.7
cryptography==3.1
Cython==0.29.21
dbus-python==1.2.16
Deprecated==1.2.13
dnspython==2.0.0
docutils==0.17.1
email-validator==1.1.3
fastapi==0.71.0
filelock==3.0.12
flake8==4.0.1
Flask==2.0.2
Flask-Admin==1.5.6
Flask-APScheduler==1.11.0
Flask-BabelEx==0.9.4
Flask-CKEditor==0.4.4.1
Flask-Cors==3.0.10
Flask-Docs==0.1.3
Flask-Excel==0.0.7
Flask-JWT-Extended==4.3.1
Flask-LogConfig==0.4.2
Flask-Login==0.5.0
Flask-Mail==0.9.1
flask-marshmallow==0.14.0
Flask-Migrate==2.5.3
Flask-Principal==0.4.0
flask-redis==0.4.0
Flask-RESTful==0.3.9
Flask-Script==2.0.6
Flask-Security==3.0.0
flask-sqlacodegen==1.1.8
Flask-SQLAlchemy==2.5.1
Flask-WTF==0.14.3
greenlet==1.1.2
gunicorn==20.1.0
h11==0.9.0
httptools==0.1.2
idna==2.10
imagesize==1.3.0
inflect==5.3.0
iniconfig==1.1.1
itsdangerous==2.0.1
Jinja2==3.0.3
jmespath==0.10.0
jsonpatch==1.32
jsonpointer==2.1
jsonschema==3.2.0
jwcrypto==0.6.0
language-selector==0.1
lml==0.0.9
ogconfig==0.4.0
logutils==0.3.5
Mako==1.1.3
MarkupSafe==2.0.1
marshmallow==3.14.0
marshmallow-sqlalchemy==0.26.1
mccabe==0.6.1
motor==2.5.1
Naked==0.1.31
netifaces==0.10.4
oauthlib==3.1.1
oss2==2.15.0
packaging==21.0
passlib==1.7.4
Pillow==7.2.0
platformdirs==2.2.0
pluggy==0.13.1
pycodestyle==2.8.0
pycparser==2.20
pycryptodome==3.12.0
pydantic==1.9.0
pyexcel==0.6.4
pyexcel-io==0.5.20
pyexcel-webio==0.1.4
pyfiglet==0.8.post1
pyflakes==2.4.0
Pygments==2.11.2
PyGObject==3.36.0
PyJWT==2.3.0
pymacaroons==0.13.0
pymongo==3.12.3
PyMySQL==1.0.2
PyNaCl==1.3.0
pyparsing==2.4.7
pyrsistent==0.17.3
pytest==6.2.4
pandas==1.4.1
python-dateutil==2.8.1
python-editor==1.0.4
pytz==2020.1
PyYAML==5.3.1
pyzt==1.0.1
redis==4.0.2
requests==2.26.0
shellescape==3.8.1
simplejson==3.17.2
six==1.16.0
sniffio==1.2.0
snowballstemmer==2.2.0
soupsieve==2.2.1
speaklater==1.3
Sphinx==4.3.0
sphinxcontrib-applehelp==1.0.2
sphinxcontrib-devhelp==1.0.2
sphinxcontrib-htmlhelp==2.0.0
sphinxcontrib-jsmath==1.0.1
sphinxcontrib-qthelp==1.0.3
sphinxcontrib-serializinghtml==1.1.5
SQLAlchemy==1.3.24
SQLAlchemy-Utils==0.38.2
ssh-import-id==5.10
starlette==0.17.1
termcolor==1.1.0
texttable==1.6.3
tornado==6.0.4
typing-extensions==3.10.0.2
tzlocal==2.1
urllib3==1.25.10
uvicorn==0.11.3
uvloop==0.16.0
virtualenv==20.7.2
websockets==8.1
Werkzeug==2.0.2
wrapt==1.13.3
wsproto==0.15.0
WTForms==2.3.3
xmltodict==0.12.0
zipp==3.6.0

其他规范:

  • 每一个项目都要写好readme.md文件,写不同环境切换时需要修改的事项和文件目录,比如:不可或缺的基础数据,切换时需要更改的域名。需要依赖的第三方包或者插件等。

  • 公司的接口请求方式只有两种:get和post。