前几天写了一下 nginx + webpy + fastcgi cache 配置详解,光配置还是不够的,启用缓存之后还需要purge缓存,今天分享下如何使用python来purge nginx的缓存。 #!/usr/bin/env python # coding: utf-8 import socket from config import configParser,logger import re from urlparse import urlparse __author__ = 'outofmemory.cn' purgeHost = 'outofmemory.cn' purgeIP = '127.0.0.1' purgePort = 80 def purge(url): urlParts = urlparse(url) page = '%s%s%s' % (urlParts.path, ('?' if urlParts.query else ''), urlParts.query or '') s = None try: logger.info('purge %s' %(url,)) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((purgeIP, purgePort)) s.send('GET /purge/' + page +' HTTP/1.1\nHost:' + purgeHost + '\n\n') data = s.recv(1024) ###检查是否有“404 Not Found” 或 "Successful purge" 字符串 success = "Successful purge" found = "404 Not Found" if re.search(success,data): #purge success return 0 elif re.search(found,data): #print "该页面没有被缓存<br>" return 1 else: #print "未知错误...<br>" logger.error('nginx purge url response:%s' % (data,)) return -1 except Exception,ex: logger.error('nginx purge error : %s' % (ex,)) return -1 finally: if s: s.close() 这段代码使用socket来purge缓存,需要指定连接的IP和端口。这是因为在配置时指定了允许访问的IP地址,其他地址拒绝访问。 (责任编辑:IT) |