A project needs to upload pictures, the beginning of a colleague will 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 interface to the mobile phone terminal, At the end of the mobile phone will cause some bugs, after the change of code requirements to replace the previous URI to the relative URL (/m/getimg?filename=xxx.jpg), because the image is embedded into the content with an IMG tag and a label to show the larger picture, 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 Pymongo
import re from
Stringio import stringio
conn = Pymongo. Connection ()
db = Conn.test
def 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 () C23/>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 ()