就为了实现动态获取远程服务器上的图片,走了不少弯路,比如用paramiko,结果得远程服务器安装SSH,但是我服务器版本不适宜,反正遇到了不少坑,看了很多博客,集众人之所长,啧啧,最终成功实现,感谢感谢! # --*-- coding:utf-8 --*-- import apscheduler import time from apscheduler.schedulers.blocking import BlockingScheduler import pandas as pd import pymysql # 添加下面两句,那么3可以向下兼容2 pymysql.install_as_MySQLdb() import MySQLdb import subprocess import os import urllib import time from urllib.request import urlretrieve import paramiko def download(IMAGE_URL, SAVE_PATH): urlretrieve(IMAGE_URL, SAVE_PATH) def connect_mysql(): db_config = { 'host':'',#host 'port':3306, 'user':'root', 'password':'root', 'db':'mianya',#需要连接的数据库 'charset':'utf8'#编码' } try: cms = pymysql.connect(**db_config) cur = cms.cursor()#获取一个游标 #cur.execute('flush privileges;')#必须实时更新数据 cur.execute('select * from my_message_pic where number = 0;') data = cur.fetchall() print(len(data)) for d in data:#打印查询的数据 print('id: ' + str(d[0]) + '\t' + 'uptime: ' + str(d[3]) + '\t' + 'path: ' + str(d[5]) + '\t' + 'number: ' + str(d[8])) IMAGE_URL = "" #下载图片的路径 SAVE_PATH = "" #保存路径 download(IMAGE_URL, SAVE_PATH) cur.execute("update my_message_pic set number = 1 where id =" + str(d[0]) + ";") cur.close() except Exception as e: print(e) sched = BlockingScheduler() sched.add_job(connect_mysql, 'interval', seconds=10)#隔10秒跑一次 sched.start()
试了一下,下述三种下载方式,第一种最快
def urllib_download(): from urllib.request import urlretrieve urlretrieve(IMAGE_URL, 'C:/Users/ASUS/Desktop/image/img1.png') def request_download(): import requests r = requests.get(IMAGE_URL) with open('C:/Users/ASUS/Desktop/image/img2.png', 'wb') as f: f.write(r.content) def chunk_download(): import requests r = requests.get(IMAGE_URL, stream=True) with open('C:/Users/ASUS/Desktop/image/img3.png', 'wb') as f: for chunk in r.iter_content(chunk_size=32): f.write(chunk)