本文整理汇总了Python中Core.db.session.add函数的典型用法代码示例。如果您正苦于以下问题:Python add函数的具体用法?Python add怎么用?Python add使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
def run(self, request, **kwargs):
try:
user, cookie, key, planet_id = self.router(request)
response = self.execute(request, user, **kwargs)
session = Session()
session.add(PageView(page = self.name,
full_request = request.get_full_path(),
username = user.name,
session = key,
planet_id = user.planet.id if user.planet else None,
hostname = request.META['REMOTE_ADDR'],))
session.commit()
if cookie is not None:
response.set_cookie(SESSION_KEY, cookie, expires=request.session.expire)
if planet_id is False:
response.delete_cookie(PLANET_KEY)
elif planet_id is not True:
response.set_cookie(PLANET_KEY, planet_id, expires=datetime.now()+timedelta(days=65))
return response
except UserError, e:
return self.login_page(request, str(e))
示例2: authenticate
def authenticate(self, request):
request.session = None
request.user = None
key = request.COOKIES.get(SESSION_KEY)
if key:
auth = Arthur.load(key, datetime.now())
if auth is None:
raise UserError("Your session has expired, please login again.")
if request.path == LOGOUT:
session.delete(auth)
session.commit()
raise UserError("Logged out.")
request.session = auth
return auth.user, None, key
elif (request.POST.get(USER) and request.POST.get(PASS)):
user = User.load(name=request.POST.get(USER), passwd=request.POST.get(PASS))
if user is None:
raise UserError("Invalid user.")
else:
key = self.generate_key(user)
auth = Arthur(key=key, expire=datetime.now()+timedelta(days=1), user=user)
session.query(Arthur).filter(Arthur.user == user).delete()
session.add(auth)
session.commit()
request.session = auth
return user, key, key
else:
return None, None, None
示例3: main
def main(url = Config.get("URL", "ships"), debug=False):
req = urllib2.Request(url)
req.add_header('User-Agent', useragent)
stats = urllib2.urlopen(req).read()
session.execute(Ship.__table__.delete())
if Config.get("DB", "dbms") == "mysql":
session.execute(text("ALTER TABLE ships AUTO_INCREMENT=1;", bindparams=[false]))
else:
session.execute(text("SELECT setval('ships_id_seq', 1, :false);", bindparams=[false]))
for line in sre.findall(stats):
ship = Ship()
line = list(line)
for index, key in enumerate(keys):
if line[index] in mapping:
line[index] = mapping[line[index]]
elif line[index].isdigit():
line[index] = int(line[index])
if line[index] not in ('-', '',):
setattr(ship,key,line[index])
ship.total_cost = ship.metal + ship.crystal + ship.eonium
if debug: print "%12s%12s%12s%12s" % (ship.name, ship.class_, ship.race, ship.type,)
session.add(ship)
session.commit()
session.close()
示例4: execute
def execute(self, message, user, params):
chan = params.group(1)
access = params.group(2)
if not access.isdigit():
try:
access = Config.getint("Access", access)
except Exception:
message.reply("Invalid access level '%s'" % (access,))
return
else:
access = int(access)
if access > user.access:
message.reply("You may not add a user with higher access to your own")
return
try:
session.add(Channel(name=chan, userlevel=access, maxlevel=user.access))
session.commit()
message.reply("Added chan %s at level %s" % (chan, access))
message.privmsg("set %s autoinvite on" % (chan,), Config.get("Services", "nick"))
message.privmsg("invite %s" % (chan,), Config.get("Services", "nick"))
except IntegrityError:
session.rollback()
message.reply("Channel %s already exists" % (chan,))
示例5: execute
def execute(self, page, uid, pa_id, gid=None):
scanlog("Scan: %s (group: %s)" %(pa_id,gid,))
page = decode(page)
m = re.search('>([^>]+) on (\d+)\:(\d+)\:(\d+) in tick (\d+)', page)
if not m:
scanlog("Expired/non-matchinng scan (id: %s)" %(pa_id,))
return
scantype = m.group(1)[0].upper()
x = int(m.group(2))
y = int(m.group(3))
z = int(m.group(4))
tick = int(m.group(5))
m = re.search("<p class=\"right scan_time\">Scan time: ([^<]*)</p>", page)
scantime = m.group(1)
planet = Planet.load(x,y,z,)
try:
Q = session.query(Scan).filter(Scan.pa_id == pa_id).filter(Scan.planet_id == None)
if Q.count() > 0:
scan = Q.first()
else:
scan = Scan(pa_id=pa_id, scantype=scantype, tick=tick, time=scantime, group_id=gid, scanner_id=uid)
session.add(scan)
if planet:
planet.scans.append(scan)
session.commit()
scan_id = scan.id
except IntegrityError, e:
session.rollback()
scanlog("Scan %s may already exist: %s" %(pa_id,str(e),))
return
示例6: new
def new(self, message, user, params):
tick = Updates.current_tick()
comment = params.group(3) or ""
when = int(params.group(1))
if when < PA.getint("numbers", "protection"):
eta = when
when += tick
elif when <= tick:
message.alert(
"Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick)
)
return
else:
eta = when - tick
if when > 32767:
when = 32767
attack = Attack(landtick=when, comment=comment)
session.add(attack)
for coord in re.findall(loadable.coord, params.group(2)):
if not coord[4]:
galaxy = Galaxy.load(coord[0], coord[2])
if galaxy:
attack.addGalaxy(galaxy)
else:
planet = Planet.load(coord[0], coord[2], coord[4])
if planet:
attack.addPlanet(planet)
session.commit()
message.reply(str(attack))
示例7: run
def run(self, message):
m = self.match(message, self.commandre)
if m is None:
if self.match(message, self.helpre) is not None:
self.help(message)
return
command = m.group(2)
try:
route, subcommand, user, params = self.router(message, command)
route(message, user, params)
session = Session()
session.add(Command(command_prefix = message.get_prefix(),
command = self.name,
subcommand = subcommand,
command_parameters = self.hide_passwords(self.name, message.get_msg()[len(m.group(1))+1:].strip()),
nick = message.get_nick(),
username = "" if user is True else user.name,
hostname = message.get_hostmask(),
target = message.get_chan() if message.in_chan() else message.get_nick(),))
session.commit()
session.close()
except PNickParseError:
message.alert(self.PParseError)
except UserError:
message.alert(self.AccessError)
except PrefError:
message.alert(self.PrefError)
except ChanParseError, e:
message.alert(self.ChanError%e)
示例8: invite
def invite(self, message, user, params):
person = params.group(1)
if person.lower() == Config.get("Connection","nick").lower():
message.reply("I am already here, shitface.")
return
u = User.load(name=person,access="member")
if u is not None:
message.reply("Stupid %s, that wanker %s is already a member."%(user.name,person))
return
if self.is_already_proposed_invite(person):
message.reply("Silly %s, there's already a proposal to invite %s."%(user.name,person))
return
if not self.member_count_below_limit():
message.reply("You have tried to invite somebody, but we have too many losers and I can't be bothered dealing with more than %s of you."%(Config.getint("Alliance", "members"),))
return
anc = user.has_ancestor(person)
if anc is True:
message.reply("Ew, incest.")
return
if anc is None:
message.reply("Filthy orphans should be castrated.")
return
prop = Invite(id=self.new_prop_id(), proposer=user, person=person, comment_text=params.group(2))
session.add(prop)
session.commit()
reply = "%s created a new proposition (nr. %d) to invite %s." %(user.name, prop.id, person)
reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,)
message.reply(reply)
示例9: suggest
def suggest(self,message,user,params):
prop = Suggestion(id=self.new_prop_id(), proposer=user, comment_text=params.group(1))
session.add(prop)
session.commit()
reply = "%s created a new proposition (nr. %d) : %s" %(user.name,prop.id,prop.comment_text)
reply+= " When people have been given a fair shot at voting you can call a count using !prop expire %d."%(prop.id,)
message.reply(reply)
示例10: execute
def execute(self, message, user, params):
params = params.group(1)
params=self.timestampre.sub(' ',params).strip()
session.add(Slogan(text=params))
session.commit()
message.reply("Added your shitty slogan: "+params)
示例11: add_record
def add_record(dct):
record = rclass()
for key in dct.keys():
setattr(record, key, dct[key])
if __name__ == '__main__':
print "%12s%12s" % (key, dct[key])
if gen_mods:
record.gen_mods()
session.add(record)
示例12: __init__
def __init__(self, message, m):
scanlog(asctime())
try:
pnick = "(%s)" % message.get_pnick()
except:
pnick = ""
scanlog("Galaxy status from %s%s" % (message.get_nick(), pnick))
target_x=m.group(1)
target_y=m.group(2)
target_z=m.group(3)
owner_x=m.group(4)
owner_y=m.group(5)
owner_z=m.group(6)
mission=m.group(7)
fleetname=m.group(8)
# race=m.group(10)
fleetsize=m.group(11)
eta=m.group(12)
if mission == "A":
mission = "Attack"
elif mission == "D":
mission = "Defend"
elif mission == "R":
mission = "Return"
target=Planet.load(target_x,target_y,target_z)
if target is None:
return
owner=Planet.load(owner_x,owner_y,owner_z)
if owner is None:
return
curtick=Updates.current_tick()
landing_tick = int(eta) + int(curtick)
scanlog("%s:%s:%s %s:%s:%s '%s' %s %s eta %s" % (owner_x,owner_y,owner_z,target_x,target_y,target_z,fleetname,fleetsize,mission,eta))
fleet = FleetScan(owner=owner, target=target, fleet_size=fleetsize, fleet_name=fleetname, landing_tick=landing_tick, mission=mission)
fleet.in_cluster = owner_x == target_x
fleet.in_galaxy = fleet.in_cluster and owner_y == target_y
try:
session.add(fleet)
session.commit()
except IntegrityError,e:
session.rollback()
print "Exception in galstatus: "+e.__str__()
scanlog("Exception in galstatus: "+e.__str__())
traceback.print_exc()
示例13: new
def new(self, message, user, params):
tick = Updates.current_tick()
comment = params.group(4) or ""
when = int(params.group(1))
waves = params.group(2) or Config.get("Misc", "attwaves")
if when < PA.getint("numbers", "protection"):
when += tick
elif when <= tick:
message.alert("Can not create attacks in the past. You wanted tick %s, but current tick is %s." % (when, tick,))
return
if when > 32767:
when = 32767
attack = Attack(landtick=when,comment=comment,waves=int(waves))
session.add(attack)
for coord in re.findall(loadable.coord, params.group(3)):
if not coord[4]:
galaxy = Galaxy.load(coord[0],coord[2])
if galaxy:
attack.addGalaxy(galaxy)
else:
planet = Planet.load(coord[0],coord[2],coord[4])
if planet:
attack.addPlanet(planet)
session.commit()
message.reply(str(attack))
# Request scans
if Config.has_option("Misc", "attscans"):
scantypes = Config.get("Misc", "attscans")
else:
scantypes = ""
for stype in scantypes:
for p in attack.planets:
scan = p.scan(stype)
if scan and (int(tick) == scan.tick):
return
else:
req = Request(target=p, scantype=stype, dists=0)
user.requests.append(req)
session.commit()
push("request", request_id=req.id, mode="request")
if scantypes:
message.reply("Scans requested: %s" % (scantypes))
示例14: get_user
def get_user(self, name, channel, pnick=None, pnickf=None):
# Regular user check
if (pnick is None) and (pnickf is None):
# This shouldn't happen
return None
nick = self.Nicks.get(name)
if (nick and nick.puser) is not None:
# They already have a user associated
pnick = nick.puser
elif pnickf is not None:
# Call the pnick function, might raise PNickParseError
try:
pnick = pnickf()
except PNickParseError:
return None
user = User.load(name=pnick)
if user is None and Config.getboolean("Misc", "autoreg"):
if nick and not nick.puser:
if "galmate" in Config.options("Access"):
access = Config.getint("Access", "galmate")
else:
access = 0
user = User.load(name=pnick, active=False)
if user is None:
user = User(name=pnick, access=access)
session.add(user)
else:
user.active = True
user.access = access
session.commit()
if user is None:
return None
if (nick is not None) and self.mode_is("rapid", "join"):
if self.Pusers.get(user.name) is None:
# Add the user to the tracker
self.Pusers[user.name] = Puser(user.name)
if nick.puser is None:
# Associate the user and nick
nick.puser = user.name
self.Pusers[user.name].nicks.add(nick.name)
# Return the SQLA User
return user
示例15: execute
def execute(self, message, user, params):
chan = params.group(1)
if "galmate" in Config.options("Access"):
access = Config.getint("Access","galmate")
else:
access = 0
try:
session.add(Channel(name=chan, userlevel=access, maxlevel=access))
session.commit()
message.reply("Added your galchannel as %s (if you didn't add me to the channel with at least access 24 first, I'm never going to bother joining)" % (chan,))
message.privmsg("set %s autoinvite on" %(chan,),'P');
message.privmsg("invite %s" %(chan,),'P');
except IntegrityError:
session.rollback()
message.reply("Channel %s already exists" % (chan,))