脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 如何把docker-compose.yaml导入到数据库相关条目里

python 如何把docker-compose.yaml导入到数据库相关条目里

2021-08-25 00:29怠惰的小小白 Python

这篇文章主要介绍了python 如何把docker-compose.yaml导入到数据库相关条目里?下面小编就为大家介绍一下实现方式,一起跟随小编过来看看吧

实现将docker-compose.yaml导入相关的数据库条目的功能,利用python脚本,yaml、sqlalchemy、json等模块实现。

docker-compose.yaml

?
1
2
3
4
5
6
7
8
_version: "1"
services:
  webapp:
   build:
    context: ./dir
    dockerfile: Dockerfile-alternate
    args:
     buildno: 1

python deme文件。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
import yaml
import traceback
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, DateTime, Index, Integer, String, Text, text, BigInteger
from sqlalchemy.ext.declarative import declarative_base
import datetime
import json
import base64
 
"""
作用:将docker-compose.yaml导入到数据库的docker-compose表中。
docker-compose表创建语句:
 CREATE TABLE `docker_compose` (
 `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
 `services` text NOT NULL COMMENT '@desc services',
 `creator` int(11) DEFAULT '0',
 `modifier` int(11) DEFAULT '0',
 `gmt_created` datetime NOT NULL,
 `gmt_modified` datetime NOT NULL,
 `_version` varchar(64) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1092 DEFAULT CHARSET=utf8
"""
 
 
def now():
  return datetime.datetime.now()
 
 
BASE = declarative_base()
 
 
class DockerCompose(BASE):
  __tablename__ = 'docker_compose'
 
  id = Column(BigInteger, primary_key=True)
  services = Column(Text, nullable=False)
  _version = Column(String(64))
  creator = Column(Integer, server_default=text("'0'"))
  modifier = Column(Integer, server_default=text("'0'"))
  gmt_created = Column(DateTime, nullable=False)
  gmt_modified = Column(DateTime, nullable=False)
 
 
def get_session(db_connection):
  """
  db connection api
  :param db_connection:
  :return:
  """
  DB_URL = 'mysql+pymysql://%s' % (db_connection,)
  engine = create_engine(DB_URL, pool_size=25, pool_recycle=3600, echo=False)
  Session = sessionmaker(bind=engine)
  return Session()
 
 
def load_yaml(filename):
  try:
    with open(filename, 'r') as fh:
      return yaml.safe_load(fh)
  except (IOError, yaml.YAMLError) as e:
 
    raise Exception(u"{}".format(traceback.format_exc()))
 
 
def import_engine_compose(instance_config, dbConnection):
  services = instance_config['services']
  _version = instance_config.get('_version')
  session = get_session(dbConnection)
 
  docker_compose = DockerCompose(
    gmt_created=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    gmt_modified=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
    creator=999,
    modifier=999,
    _version=_version,
    services=json.dumps(services)
  )
 
  session.add(docker_compose)
  session.commit()
 
 
def main(dbConnection, filepath="docker_compose.yaml"):
  docker_compose_config = load_yaml(filepath)
  import_engine_compose(docker_compose_config, dbConnection)
 
 
if __name__ == '__main__':
  dbConnection = "xxx"
 
  DB_CONNECTION = base64.b64decode(dbConnection)
  main(DB_CONNECTION)

补充:docker-compose.yaml的编写

当我们打包好了镜像的时候,一个一个区整理的时候,也是很浪费功夫,尤其是我们修改了一些代码的时候

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
version: "2"
services:
  mysql:
    image: mysql:mysql
    hostname: mysql
    ports:
      - "3306:3306"
    volumes:
      - "/data/mysql:/var/lib/mysql"
    restart: always
  backend:
    image: backend:0.5
    command: "python3 main.py"
    hostname: backend
    volumes:
      - "/data/files:/app/files"
    network_mode: "host"
    depends_on:
      - mysql
    restart: always
  frontend:
    image: frontend:0.5
    hostname: frontend
    volumes:
      - "/Users/gaven/Desktop/anji/frontend/web/nginx.conf:/etc/nginx/nginx.conf"
      - "/Users/gaven/Desktop/anji/frontend/web/default.conf:/etc/nginx/conf.d/default.conf"
    ports:
      - "80:80"
    network_mode: "host"
    restart: always

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。如有错误或未考虑完全的地方,望不吝赐教。

原文链接:https://blog.csdn.net/qq_35462323/article/details/109723934

延伸 · 阅读

精彩推荐