2020系统综合实践 第5次实践作业

文件准备

(1)文件结构

(2)Dockerfile

FROM python:3
MAINTAINER Tinor
WORKDIR /usr/local/app
COPY requirements.txt ./ # 添加依赖声明文件
RUN pip install --no-cache-dir -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt #换成清华源
ENTRYPOINT ["python"]
CMD ["helloworld.py"] #默认打开文件

(3)依赖文件
requirements.txt

PyMySQL
opencv-python

(4)helloworld.py

print("helloworld")

(5)date.py

import calendar
yy = int(input("输入年份: "))
mm = int(input("输入月份: "))
print(calendar.month(yy,mm))

(6)database.py

# 由于使用的是第二次试验的mysql镜像,数据库中已有Student表
# 该程序实现的功能是先查找并打印Student表中的所有数据
# 然后向Student表中插入一条数据
# 最后再次查找并打印Student表中的所有数据
import pymysql
 
# 打开数据库连接
db = pymysql.connect("tinor_mysql", "root", "123456", "docker_mysql")

# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT * FROM Student"

try:
   # 执行SQL语句
   cursor.execute(sql)

   # 获取所有记录列表
   results = cursor.fetchall()
   print("Before insert!")
   for row in results:
      id = row[0]
      name = row[1]
      sex = row[2]

       # 打印结果
      print ("Sn0:%s,Sname:%s,Ssex:%s" % (id, name, sex))

except:
   print ("Error: unable to fetch data")

# SQL 插入语句
sql = """INSERT INTO Student(Sno,Sname,Ssex) 
         VALUES ('031702442', 'CJJ','Male')"""

try:
   # 执行sql语句
   cursor.execute(sql)

   # 提交到数据库执行
   db.commit()
   print("
successfully inserted!
")

except:
   # 如果发生错误则回滚
   db.rollback()

# SQL 查询语句
sql = "SELECT * FROM Student"

try:
   # 执行SQL语句
   cursor.execute(sql)

   # 获取所有记录列表
   results = cursor.fetchall()
   print("After insert!")
   for row in results:
      id = row[0]
      name = row[1]
      sex = row[2]

       # 打印结果
      print ("Sn0:%s,Sname:%s,Ssex:%s" % (id, name, sex))

except:
   print ("Error: unable to fetch data")

# 关闭数据库连接
db.close()

(7)opencv.py

# 该程序实现的是将一张图片逆时针旋转90度并保存旋转后的图片
import cv2
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_result.jpg", dst, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
print('successfully rotated and saved as test_result.jpg')

环境构建和程序执行

(1)构建镜像

docker build -t mypython .


(2)运行mysql容器
用的是实验二的镜像

docker run --name tinor_mysql -d -p 2441:2441 tinor_mysql

(3)运行并进入python容器

docker run -it -v /home/tinor/EX5_python/pythonfile:/usr/local/app --link=tinor_mysql:tinor_mysql -d mypython #这里同时实现了将本地文件目录挂载至容器内的工作目录
docker exec -it [容器id] /bin/bash 

用ls命令查看工作目录下的文件可以发现准备的4个程序已经成功部署到容器中了


(4)运行helloworld.py

(5)运行date.py

(6)运行database.py

在数据库中查看是否成功插入数据

(7)运行opencv.py



实验报告

(1)遇到的问题
问题1:

解决:


把Dockerfile中这一行注释删掉就可以了
问题2:

解决:

(2)经验和感想
这次实验相对简单,"人生苦短,我用python!",python从来没让我失望过。遇到的主要问题还是在数据库操作那一块,如果不想浪费时间可以先看看其他同学踩过的坑。
(3)耗时
2h 30mins

原文地址:https://www.cnblogs.com/Tinor/p/12924332.html