def __init__(self, filename, flag='c', protocol=None, writeback=False):
import dbm
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
python类open()的实例源码
def open(filename, flag='c', protocol=None, writeback=False):
"""Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
dbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface.
"""
return DbfilenameShelf(filename, flag, protocol, writeback)
def __init__(self, filename, flag='c', protocol=None, keyencoding='utf-8'):
self.db = filename
self.flag = flag
self.dict = {}
with dbm.open(self.db, self.flag) as db:
for k in db.keys():
v = BytesIO(db[k])
self.dict[k] = Unpickler(v).load()
shelve.Shelf.__init__(self, self.dict, protocol, False, keyencoding)
def sync(self):
with dbm.open(self.db, self.flag) as db:
for k, v in self.dict.items():
f = BytesIO()
p = Pickler(f, protocol=self._protocol)
p.dump(v)
db[k] = f.getvalue()
db.sync()
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def __init__(self, filename, mode, perm):
import dbm
self.db = dbm.open(filename, mode, perm)
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def query(self, word):
import requests
from bs4 import BeautifulSoup
sess = requests.Session()
headers = {
'Host': 'open.iciba.com',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:50.0) Gecko/20100101 Firefox/50.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate'
}
sess.headers.update(headers)
url = 'http://open.iciba.com/huaci_new/dict.php?word=%s' % (word)
try:
resp = sess.get(url, timeout=100)
text = resp.text
pattern = r'(<div class=\\\"icIBahyI-group_pos\\\">[\s\S]+?</div>)'
text = re.search(pattern, text).group(1)
except:
return None
if (resp.status_code == 200) and (text):
soup = BeautifulSoup(text, 'lxml')
ps = soup.find_all('p')
trans = []
for item in ps:
transText = item.get_text()
transText = re.sub(
r'\s+', ' ', transText.replace('\t', '')).strip()
if transText:
trans.append(transText)
return '\n'.join(trans)
else:
return None
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def __init__(self, filename, flag='c', protocol=None, writeback=False):
import dbm
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
def open(filename, flag='c', protocol=None, writeback=False):
"""Open a persistent dictionary for reading and writing.
The filename parameter is the base filename for the underlying
database. As a side-effect, an extension may be added to the
filename and more than one file may be created. The optional flag
parameter has the same interpretation as the flag parameter of
dbm.open(). The optional protocol parameter specifies the
version of the pickle protocol (0, 1, or 2).
See the module's __doc__ string for an overview of the interface.
"""
return DbfilenameShelf(filename, flag, protocol, writeback)
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def load(self, id):
# overridable callback for external storage, do not call directly
try:
file = open(self.path(id), 'rb')
except IOError:
return None
blob = file.read()
file.close()
return blob
def save(self, id, blob):
# overridable callback for external storage, do not call directly
file = open(self.path(id), 'wb')
file.write(blob)
file.close()
return id
def startup(self, *args, **kwargs):
'''Supports path= to specify a location, otherwise assumes the
current directory.
'''
path = kwargs.get('path', '.')
self._path = '%s/%s' % (path, self.name)
self._db = dbm.open(self._path, 'c')
return [ ]
def open(file, flag='r', mode=0666):
"""Open or create database at path given by *file*.
Optional argument *flag* can be 'r' (default) for read-only access, 'w'
for read-write access of an existing database, 'c' for read-write access
to a new or existing database, and 'n' for read-write access to a new
database.
Note: 'r' and 'w' fail if the database doesn't exist; 'c' creates it
only if it doesn't exist; and 'n' always creates a new database.
"""
# guess the type of an existing database
from whichdb import whichdb
result=whichdb(file)
if result is None:
# db doesn't exist
if 'c' in flag or 'n' in flag:
# file doesn't exist and the new
# flag was used so use default type
mod = _defaultmod
else:
raise error, "need 'c' or 'n' flag to open new db"
elif result == "":
# db type cannot be determined
raise error, "db type could not be determined"
else:
mod = __import__(result)
return mod.open(file, flag, mode)
def set(self, **kw):
"""
Set this object by setting one of its known formats.
This method only allows one to set one format at a time.
Subsequent calls will clear the object first. The point of all
this is to let the object's internal converters handle mustering
the object into whatever format you need at the moment.
"""
if len(kw) == 1:
name = kw.keys()[0]
if name in self.formats:
self.clear()
setattr(self, name, kw[name])
return
if name == "PEM":
self.clear()
self._set_PEM(kw[name])
return
if name == "Base64":
self.clear()
self.DER = base64.b64decode(kw[name])
return
if name == "Auto_update":
self.filename = kw[name]
self.check_auto_update()
return
if name in ("PEM_file", "DER_file", "Auto_file"):
f = open(kw[name], "rb")
value = f.read()
f.close()
self.clear()
if name == "PEM_file" or (name == "Auto_file" and looks_like_PEM(value)):
self._set_PEM(value)
else:
self.DER = value
return
raise rpki.exceptions.DERObjectConversionError("Can't honor conversion request %r" % (kw,))
def check_auto_update(self):
"""
Check for updates to a DER object that auto-updates from a file.
"""
if self.filename is None:
return
try:
filename = self.filename
timestamp = os.stat(self.filename).st_mtime
if self.timestamp is None or self.timestamp < timestamp:
logger.debug("Updating %s, timestamp %s",
filename, rpki.sundial.datetime.fromtimestamp(timestamp))
f = open(filename, "rb")
value = f.read()
f.close()
self.clear()
if looks_like_PEM(value):
self._set_PEM(value)
else:
self.DER = value
self.filename = filename
self.timestamp = timestamp
except (IOError, OSError), e:
now = rpki.sundial.now()
if self.lastfail is None or now > self.lastfail + self.failure_threshold:
logger.warning("Could not auto_update %r (last failure %s): %s", self, self.lastfail, e)
self.lastfail = now
else:
self.lastfail = None
def __init__(self, filename, keyno = 0):
try:
try:
import gdbm as dbm_du_jour
except ImportError:
import dbm as dbm_du_jour
self.keyno = long(keyno)
self.filename = filename
self.db = dbm_du_jour.open(filename, "c")
except:
logger.warning("insecure_debug_only_rsa_key_generator initialization FAILED, hack inoperative")
raise