清单解析器服务化
1 将项目文件导入服务器
准备好以下文件
(1)Dockerfile-parser
From swr.cn-north-4.myhuaweicloud.com/zt-sjzn-znzj-pd/costestimation-base:3.0 #基础镜像
MAINTAINER "zhanghc" "zhanghc@glodon.com" # 维护人
ENV LC_ALL "zh_CN.UTF-8" #编码环境
COPY serving/ /workspace/serving/ # 将上图中serving中的文件复制到docker容器内
RUN chmod +x /workspace/serving/run.sh # 赋权给run.sh
RUN pip install -i https://ai-sjzn-project:AP5nT2xx5sXvwoTi8iYBpA1ZZcr@packages.glodon.com/artifactory/api/pypi/PyPI-AIplatform-open/simple --extra-index-url https://pypi.tuna.tsinghua.edu.cn/simple parsercode==2.0.0 #将组件沉淀生成的python包安装到docker容器内
WORKDIR /workspace/serving # 工作路径
ENTRYPOINT ["/workspace/serving/run.sh]
(2)mysql_config.json
配置数据库信息
{
"host": "192.168.8.51",
"user": "root",
"password": "123456",
"database": "gld_cost_estimation",
"port": "3308",
"charset": "utf8"
}
(3)uwsgi_main.py
调用解析器,定义wsgi接口,以供http请求。
# -*- coding:UTF-8 -*-
import os, sys, json
import pandas as pd
import requests
curPath = os.path.abspath(os.path.dirname(__file__))
#rootPath = os.path.split(curPath)[0]
sys.path.append(curPath)
# sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import parser_api.parser_api as pa
dbid='1710'
chapter_code='all'
mysql_config_file=os.path.join(os.path.dirname(__file__),'mysql_config.json')
p=pa.PARSER_API(dbid, chapter_code, mysql_config_file)
def get_result(data):
ret = p.get_parser_result(data['itemcode'], data['spec_name'], data['spec'])
#print("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!",ret)
#return (ret)
return ret
def application(environ, start_response):
# 加入logging
# fileConfig(log_file_path)
# logger = logging.getLogger(name="TimedRotatingFileHandler")
try:
request_body_size = int(environ.get("CONTENT_LENGTH", 0))
except ValueError:
request_body_size = 0
print(f"---request_body_size---: {request_body_size}")
request_body = environ['wsgi.input'].read(request_body_size)
print(f"-----request_body------: {request_body}")
request_body = json.loads(request_body.decode().strip())
# print(f"-----after decode,request_body------: {request_body}")
print(f"---request name: {request_body['methodname']}")
########################deal with request#########################################################
finalresponse = None
if request_body['methodname'] == 'hello':
finalresponse = "Hi, there"
elif request_body['methodname'] == "get_result":
# 伟革错误编码可以在这里做修改
try:
try:
# logger.info(request_body)
finalresponse = get_result(request_body)
except ValueError:
finalresponse = {'errorString': 'Wrong formate'}
# logger.error(finalresponse)
except:
finalresponse = {'errorString': 'Unknow Error'}
# logger.error(finalresponse)
else:
print(f"------request_body['methodname']={request_body['methodname']}--------")
########################final response#########################################################
# print(f"finalresponse: {finalresponse}")
response_body = json.dumps(finalresponse, ensure_ascii=False).encode()
status = '200 OK'
response_headers = [
('Content-Type', 'application/json'),
('Content-Length', str(len(response_body)))
]
start_response(status, response_headers)
# return [json.dumps(finalresponse).encode()]
# logger.info(response_body)
return [response_body]
if __name__ == "__main__":
print("just a test")
print("test case 2")
itemcode = "031001001"
spec_name = "穿楼板套管"
spec = "1.名称:穿楼板套管፨2.规格型号:DN100"
data = {}
data['itemcode'] = itemcode
data['spec_name'] = spec_name
data['spec'] = spec
res = get_result(data)
print(res)
(3)uwsgi.conf.ini
uwsgi配置文件
[uwsgi]
http = :9001
chdir = /workspace/costparser/ #工作路径
logto = /workspace/costparser/log.log #日志
wsgi-file = ./uwsgi_main.py #wsgi文件
master = true
processes = 1 #进程
threads = 2 #线程
stats = 127.0.0.1:9091
pidfile=%(chdir)uwsgi.pid
vacuum = true
enable-threads=true
lazy-apps = true
(4)run.sh
运行uwsgi.conf.ini
#!/bin/bash
/usr/local/python3/bin/uwsgi ./uwsgi.conf.ini
2 创建镜像
#使用当前目录的 Dockerfile 创建镜像,标签为 parsercode:v1。
docker build -t parsercode:v1 .
#也可以通过 -f Dockerfile 文件的位置:
docker build -f /path/to/Dockerfile-parser .
#查看创建的镜像
docker images | grep parsercode
#删除镜像
docker rmi 镜像ID
3 创建启动容器
docker run -d -it --name test03 -p 9013:9000 parsercode:v1
#此时服务已经启动
#查看容器test03
docker ps | grep test03
#查看所有容器
docker container ls
#查看容器日志
docker logs test03
#停止、删除容器
docker stop test03
docker rm test03
4 进入容器并查看服务进程
#进入容器
docker exec -it exec test03 bash
#查看进程,验证进程是否已启动
ps -ef | grep uwsgi