本文整理汇总了Python中db.Db类的典型用法代码示例。如果您正苦于以下问题:Python Db类的具体用法?Python Db怎么用?Python Db使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Db类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, db_filename, sound_directory=None):
Db.__init__(self, db_filename)
if sound_directory is not None:
self._sound_directory = sound_directory
else:
self._sound_directory = os.path.join(
roslib.packages.get_pkg_dir('robot_eup'), 'sounds', '')
示例2: execute
def execute(self):
db = Db()
l = text_to_list(self.file_contents)
d = list_to_dict(l)
db.update_word_counts(d, self.doc_type)
db.update_doctype_count(self.count, self.doc_type)
return self.count
示例3: load_evolutionary_dependencies_from_db
def load_evolutionary_dependencies_from_db():
db = Db()
repository_id = constants.repository_map[args.repository]
types = 'CN,CM,FE,MT'
if args.coarse_grained:
types = 'CL,IN'
graphs_ed = {}
cursor = db.query("""select g.id, g.source, g.max_entities, g.min_confidence,
g.min_support, g.min_date, g.types, de.entidade1, de.entidade2, e.caminho
from dependencias_evolucionarias de
inner join grafos_de g on de.grafo = g.id
inner join entidades e on de.entidade2 = e.id
where g.repositorio = %s and g.types = %s""",
(repository_id,types))
for (id, source, max_entitites, min_confidence, min_support, min_date, types, entity1, entity2, e2_path) in cursor:
if id not in graphs_ed:
graphs_ed[id] = {
'source': source,
'max_entitites': max_entitites,
'min_confidence': min_confidence,
'min_support': min_support,
'min_date': min_date,
'types': types,
'dependencies': {}
}
if entity1 not in graphs_ed[id]['dependencies']:
graphs_ed[id]['dependencies'][entity1] = []
entity2_java_name = to_java_convention(e2_path, args.repository, True)
graphs_ed[id]['dependencies'][entity1].append(entity2_java_name)
db.close()
return graphs_ed
示例4: func_on
def func_on(self, args):
if len(args):
for a in args:
if a == "home":
self._google_user.display_timeline |= MODE_HOME
elif a == "mention":
self._google_user.display_timeline |= MODE_MENTION
elif a == "dm":
self._google_user.display_timeline |= MODE_DM
elif a == "list":
self._google_user.display_timeline |= MODE_LIST
s = Session.get_by_key_name(self._google_user.jid)
if (
not s
and self._google_user.display_timeline
and self._google_user.enabled_user
and self._google_user.msg_template.strip()
):
try:
flag = xmpp.get_presence(self._google_user.jid)
except (xmpp.Error, DeadlineExceededError):
flag = False
if flag:
Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
modes = []
if self._google_user.display_timeline & MODE_LIST:
modes.append("list")
if self._google_user.display_timeline & MODE_HOME:
modes.append("home")
if self._google_user.display_timeline & MODE_MENTION:
modes.append("mention")
if self._google_user.display_timeline & MODE_DM:
modes.append("dm")
return _("ON_MODE") % ", ".join(modes)
示例5: process
def process(self, message):
global _locale
jid = message.sender.split('/')[0]
self._google_user = GoogleUser.get_by_jid(jid)
if self._google_user is None:
self._google_user = GoogleUser.add(jid)
_locale = self._google_user.locale
self._twitter_user = Dummy()
self._api = Dummy()
if self._google_user.enabled_user:
self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
if self._twitter_user is None:
self._google_user.enabled_user = ''
else:
self._api = twitter.Api(consumer_key=config.OAUTH_CONSUMER_KEY,
consumer_secret=config.OAUTH_CONSUMER_SECRET,
access_token_key=self._twitter_user.access_token_key,
access_token_secret=self._twitter_user.access_token_secret)
self._utils = Utils(self._google_user.jid)
try:
result = self.parse_command(message.body)
except NotImplementedError:
result = _('INVALID_COMMAND')
except twitter.TwitterInternalServerError:
result = _('INTERNAL_SERVER_ERROR')
except twitter.TwitterAuthenticationError:
self._google_user.retry += 1
if self._google_user.retry >= config.MAX_RETRY:
GoogleUser.disable(self._google_user.jid)
else:
Db.set_datastore(self._google_user)
result = _('NO_AUTHENTICATION')
return result
示例6: __init__
class Announcement:
def __init__(self, max_clients, db_name, db_host, db_port, secret):
self.sequence = secret
self.base64_alt = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
self.db = Db(self, db_name, db_host, db_port)
self.announces = self.db.load_announces()
self.announces_time = int(time.time())
log.msg('Announcement __init__')
log.msg(self.announces)
self.crypt = Crypt(self.sequence)
def get_announce(self, protocol, game_name):
result = self.announces.get(game_name, {'result': '0'})
j = json.dumps(result)
c = self.crypt.crypt(j)
log.msg('Send data to client')
protocol.writeData(c)
protocol.transport.loseConnection()
# refresh announces
if int(time.time()) - self.announces_time > 15:
self.announces = self.db.load_announces()
log.msg('Announces updated')
self.announces_time = int(time.time())
示例7: parse_status
def parse_status(status):
if 'retweeted_status' in status and _user.official_retweet:
status = status['retweeted_status']
msg_dict = {'content': unescape(status['text']), 'id': str(status['id'])}
if 'user' in status:
msg_dict['username'] = status['user']['screen_name']
Db.set_cache(status)
elif 'sender' in status:
msg_dict['username'] = status['sender_screen_name']
else:
msg_dict['username'] = ''
if msg_dict['username'] and _user.bold_username:
msg_dict['username'] = '*%s*' % msg_dict['username']
username = _user.enabled_user
username_at = "@" + username
short_id = None
if username_at in msg_dict['content']:
if _user.bold_username:
msg_dict['content'] = msg_dict['content'].replace(username_at, '*%s*' % username_at)
if 'user' in status:
short_id = generate_short_id(status['id'])
msg_dict['shortid'] = '#' + str(short_id) if short_id is not None else ''
utc = pytz.utc
t = parsedate(status['created_at'])[:6]
t = datetime(*t)
utc_dt = utc.localize(t)
tz = pytz.timezone(_user.timezone)
t = tz.normalize(utc_dt.astimezone(tz))
msg_dict['time'] = t.strftime(_user.date_format.encode('UTF-8')).decode('UTF-8')
if 'source' in status:
source = re.match(r'<a .*>(.*)</a>', status['source'])
msg_dict['source'] = source.group(1) if source else status['source']
else:
msg_dict['source'] = ''
return Template(unicode(_user.msg_template)).safe_substitute(msg_dict)
示例8: func_switch
def func_switch(self, args):
length = len(args)
if length > 1:
raise NotImplementedError
else:
twitter_users = TwitterUser.get_by_jid(self._google_user.jid)
twitter_users_name = [u.twitter_name for u in twitter_users if u.twitter_name is not None]
if not length:
return (
_("NOW_USING") % self._google_user.enabled_user
+ "\n"
+ _("ALL_TWITTER_USERS_NAME") % "\n".join(twitter_users_name)
)
elif _check_username(args[0]):
twitter_users_name_ci = [x.lower() for x in twitter_users_name]
twitter_name_ci = args[0].lower()
if twitter_name_ci in twitter_users_name_ci:
i = twitter_users_name_ci.index(twitter_name_ci)
if (
not self._google_user.enabled_user
and self._google_user.display_timeline
and self._google_user.msg_template.strip()
):
try:
flag = xmpp.get_presence(self._google_user.jid)
except (xmpp.Error, DeadlineExceededError):
flag = False
if flag:
Db.set_datastore(Session(key_name=self._google_user.jid, shard=self._google_user.shard))
self._google_user.enabled_user = twitter_users_name[i]
return _("ENABLED_TWITTER_USER_CHANGED") % self._google_user.enabled_user
return _("NOT_ASSOCIATED_TWITTER_USER")
示例9: tryCountQuery
def tryCountQuery():
tableName = "test.sanityTable"
def clear(t):
db = Db()
db.activate()
db.applySql("DROP TABLE IF EXISTS %s;" %(t))
pmap = makePmap()
q = "SELECT %s FROM %s %s;" % ("count(*)", "LSST.Object", "LIMIT 10")
a = HintedQueryAction(q,
{"db" : "test"}, # Use test db.
pmap,
lambda e: None, tableName)
assert a.getIsValid()
a.chunkLimit = 6
print "Trying q=",q
clear(tableName)
print a.invoke()
print a.getResult()
db = Db()
db.activate()
db.applySql("select * from %s;" % tableName) #could print this
clear(tableName)
示例10: execute
def execute( self ):
self.server.timeout = int( self.timeout )
if not Db.fetch( "SELECT * FROM settings WHERE key='timeout'" ):
Db.execute( "INSERT INTO settings VALUES ('timeout', ?, 'INT' ) ", ( self.timeout, ), commit=True )
else:
Db.execute( "UPDATE settings SET value=? WHERE key='timeout'", ( self.timeout, ), commit=True )
print self.DONE
示例11: process
def process(self):
global _locale
try:
message = xmpp.Message(self.request.POST)
except xmpp.InvalidMessageError:
return
jid = message.sender.split("/")[0]
self._google_user = GoogleUser.get_by_jid(jid)
if self._google_user is None:
self._google_user = GoogleUser.add(jid)
_locale = self._google_user.locale
if self._google_user.enabled_user:
self._twitter_user = TwitterUser.get_by_twitter_name(self._google_user.enabled_user, self._google_user.jid)
self._api = Dummy()
if self._twitter_user is None:
self._google_user.enabled_user = ""
else:
self._api = twitter.Api(
consumer_key=config.OAUTH_CONSUMER_KEY,
consumer_secret=config.OAUTH_CONSUMER_SECRET,
access_token_key=self._twitter_user.access_token_key,
access_token_secret=self._twitter_user.access_token_secret,
)
try:
self._user = self._api.verify_credentials()
if not self._user:
raise twitter.TwitterAuthenticationError
except twitter.TwitterAuthenticationError:
self._google_user.retry += 1
if self._google_user.retry >= config.MAX_RETRY:
GoogleUser.disable(self._google_user.jid)
xmpp.send_message(self._google_user.jid, _("NO_AUTHENTICATION"))
else:
Db.set_datastore(self._google_user)
return
else:
if self._google_user.retry > 0:
self._google_user.retry = 0
if self._twitter_user.twitter_name != self._user["screen_name"]:
self._twitter_user.twitter_name = self._user["screen_name"]
self._google_user.enabled_user = self._user["screen_name"]
else:
self._twitter_user = Dummy()
self._api = Dummy()
self._user = Dummy()
utils.set_jid(self._google_user.jid)
result = self.parse_command(message.body)
if result is None:
return
if result:
while CapabilitySet("xmpp").is_enabled():
try:
message.reply(result)
except xmpp.Error:
pass
else:
break
IdList.flush(self._google_user.jid)
Db.set_datastore(self._google_user)
示例12: prets_fetchall
def prets_fetchall():
db = Db()
result = db.select("SELECT * FROM prets")
db.close()
resp = make_response(json.dumps(result))
resp.mimetype = 'application/json'
return resp
示例13: getVercode
def getVercode(teleNum):
time.sleep(5)
#在xnmsg数据库中查询对应手机号的短信内容
content=Db("xnmsg").sql("SELECT content FROM sms_sendlog_his WHERE mobile="+teleNum+" ORDER BY id DESC LIMIT 1 ")
#将短信中的验证码过滤出来,抽取字符串中的数字用filter(str.isdigit, item)
code_zc=filter(str.isdigit,content.encode('UTF-8'))
return code_zc
print code_zc
示例14: post_update
def post_update(self, status, in_reply_to_status_id=None):
url = '%s/statuses/update.json' % self.base_url
data = {'status': status}
if in_reply_to_status_id:
data['in_reply_to_status_id'] = in_reply_to_status_id
data = self._fetch_url(url, post_data=data)
Db.set_cache(data)
return data
示例15: setupIndexes
def setupIndexes(self):
p = PartitionGroup()
db = Db()
db.activate()
db.makeIfNotExist(db=metadata.getMetaDbName())
#logger.inf(p.tables)
for (t,d) in p.tables.items():
if d.has_key("index"):
self._makeIndex(t, p.partitionCols, d["index"])