Company a project needs to upload pictures, the first colleague to upload pictures after the combination of the current host to spell an absolute URL (http://192.168.1.1:888/m/getimg?filename=xxx.jpg because at the same time to provide the interface to the mobile phone terminal, In the mobile phone terminal will cause some bugs, change the code after the request to replace the previous URI to a relative URL (/m/getimg?filename=xxx.jpg), because the image is embedded in the contents of the IMG tag with a tag to display a large image, So you need to read the database and replace the content.
The script reads as follows:
#!/usr/bin/env python#-*-coding:utf-8-*-### author:cold night# email : wh_linux@126.com#import pymongoimport refr Om stringio Import stringioconn = Pymongo. Connection () db = Conn.testdef Replace_url (): regex = Re.compile (R ' ([HREF|SRC]) =["|\"]http://.*? ( /m/getimg\?. *?) ["|\ '] ') results = db[' Test '].find () db_coll = db[' Test ') def replace (r): content = r.get (' content ') if not content:return content = Stringio (content) content.seek (0) result = Stringio () for line In Content.readlines (): t = regex.sub (R ' \1= "\2" ', line) Result.write (t) result.seek (0) content = Result.read () if content: r[' content '] = content _id = r.get (' _id ') db_coll.update ({' _id ': _id} , r) results = [replace (i) for I in Results]if __name__== "__main__": Replace_url ()