本次作业为Python专题。Python是将练习使用docker容器运行Python程序。Python是很常用的程序设计语言,但是Python程序的运行依赖于提前的系统环境配置,为了降低系统配置的复杂度,同时减小资源开销,将系统环境容器化是一种解决方案。请根据Python官方镜像的镜像说明,自定义Python镜像文件,将Python程序运行起来。
参考博客

1、项目结构

2、构建容器

(1)Dockerfile

MAINTAINER ruinzly
WORKDIR /py_file
COPY requirements.txt ./
#依赖模块列表
RUN pip install --no-cache-dir --default-timeout=100 -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
 #修改源并安装依赖
VOLUME /py_file #挂在目录
ENTRYPOINT [ "python" ]
  # 实现命令行式调用容器
CMD [ "hello.py" ] 
 #设置ENTRYPOINT默认参数

(2)requirements.txt

cryptography
opencv-python

(3)建立镜像

docker build -t mypython:test

3、程序部署

相关py文件

  • hello.py
print("hello world")
  • date.py
# 引入日历模块
import calendar
 
# 输入指定年月
year = int(input("输入年份: "))
month = int(input("输入月份: "))
 
# 显示日历
print(calendar.month(year,month))

(1)hello-word

docker run --rm -v /home/ruin-master/python/py_file:/pyfile  mypython:test hello.py
##--rm: 运行结束后删除容器 

(2) 日历输出

docker run -it --rm -v /home/ruin-master/python/py_file:/pyfile  mypython:test date.py

(3) mysql操作

相关py文件

  • connection.py
 
# 打开数据库连接
db = pymysql.connect("pymysql","root","123456","python" )
 
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()
  • db.py
# 打开数据库连接
db = pymysql.connect("pymysql","root","123456","python" )
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS USER")
# 使用预处理语句创建表
sql = """CREATE TABLE USER (
         USERNAME  CHAR(20) NOT NULL,
         NUM char(20),
         AGE INT,  
         SEX CHAR(10) )"""
 
cursor.execute(sql)
# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(USERNAME,
         NUM,AGE, SEX)
         VALUES ('Ruin', '031702506', '20', 'FEMALE')"""
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()
  • search.py
 
# 打开数据库连接
db = pymysql.connect("pymysql","root","123456","python" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM USER \
       WHERE NUM = '031702506'
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      username = row[0]
      num = row[1
      age = row[2]
      sex = row[3]
     # income = row[3]
       # 打印结果
      print ("name=%s,num=%s,age=%s,sex=%s" % \
             (username, num, age, sex ))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

运行一个mysql容器(名字要和文py件对应)

docker run -itd --name pymysql -p 3306:3306 -e MYSQL_ROOT_PASSWORD=123456 mysql

连接数据库表

docker run -it --rm -v /home/ruin-master/python/py_file:/py_file --link=pymysql:pymysql mypython:test connection.py

创建和插入数据db,进入数据库看看是否成功

docker run -it --rm -v /home/ruin-master/python/py_file:/py_file --link=pymysql:pymysql mypython:test search.py

(4)opencv操作

相关py文件

  • opencv.py
import cv2

# flags传入0表示灰度图像, 1表示彩色图像
img=cv2.imread('test.jpg',flags=1)

# 获取图片尺寸
rows,cols=img.shape[:2]

# 这里的第一个参数为旋转中心,第二个为旋转角度,第三个为旋转后的缩放因子
# 可以通过设置旋转中心,缩放因子,以及窗口大小来防止旋转后超出边界的问题
M=cv2.getRotationMatrix2D((cols/2,rows/2),90,1)

# 第三个参数是输出图像的尺寸中心
dst=cv2.warpAffine(img,M,(cols,rows))

# 写入文件
cv2.imwrite("test-rotated.jpg", dst, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
print('rotated and saved.')

运行opencv

docker run -it --rm -v /home/ruin-master/python/py_file:/pyfile  mypython:test opencv.py

test.jpg

test-rotated.jpg

(5) 总结

时间花费

实验花费 写博客
4h 1h

遇到的问题

(1)mysql连接报错

解决方式:原因是没有crypyograghy,在写requirements.txt中加入crypyograghy

(2)build mypython:test镜像时time out

解决方式:写Dockerfile文件修改依赖并添加源的地方增加 --default-timeout=100 参数

总结

这次实验真的是明明显显比上次实验容易多了,花了差不多一个下午时间,做的时候还算顺利!

posted on 2020-05-19 17:12  ruinzly  阅读(215)  评论(0编辑  收藏  举报