本文整理汇总了Python中session.Session类的典型用法代码示例。如果您正苦于以下问题:Python Session类的具体用法?Python Session怎么用?Python Session使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Session类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prepSimProfile
def prepSimProfile(self):
"""
Prepare data and create User Sessions (to be simulated).
each of them will wait for the start signal.
"""
# @todo: implement a mechanism to load and use other types of RAS (from ras_type.py)
self.__ras_obj = MikrotikRas(self.__sim_profile.nas_id,
self.__sim_profile.nas_ip,
self.__sim_profile.radius_secret,
self.__sim_profile.aaa_server_ip)
# @todo: we better save and keep track of the used IP
ips = []
for ip in IPy.IP( self.__sim_profile.user_ips ):
if str(ip).endswith("0") or "255" in str(ip):
continue
ips.append( str(ip) )
for i in xrange( self.__sim_profile.total_sessions ):
session_type = random.choice( self.__sim_profile.session_types )
self.__start_sessions[ session_type ] = 1 + self.__start_sessions.get(session_type, 0)
username, password = self.__genUserPass(i)
sess = Session(session_type, self.__ready_event,
username, password,
ips.pop(0), self.__ras_obj)
sess.start()
self.__sessions.append(sess)
示例2: get_responses
def get_responses(self, id_=1):
session = Session()
bbs = session.query(BBS).filter(BBS.id == id_).one()
responses = [ res.toDict() for res in bbs.responses]
responses.reverse()
return responses
示例3: AppDelegate
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, app):
self.session = None
self.init_status_bar()
self.init_menu()
def init_status_bar(self):
self.status_bar = NSStatusBar.systemStatusBar()
self.status_item = self.status_bar.statusItemWithLength_(NSVariableStatusItemLength)
self.status_item.setHighlightMode_(1)
icon = NSImage.alloc().initWithContentsOfFile_('icon.png')
self.status_item.setImage_(icon)
def init_menu(self):
self.menu = NSMenu.alloc().init()
self.menu_item_start = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Start', 'start:', '')
self.menu.addItem_(self.menu_item_start)
menu_item_quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
self.menu.addItem_(menu_item_quit)
self.status_item.setMenu_(self.menu)
def start_(self, notification):
if self.session != None:
self.session.stop()
self.session = Session()
self.session.start()
示例4: post
def post(self):
username = self.get_argument("username", "")
password = self.get_argument("password", "")
error_messages = list()
if username == "" or password == "":
error_messages.append("参数不能为空")
self.render("login.html", error_messages=error_messages, username="")
return
user = self.db.get("SELECT * FROM accounts WHERE username = %s", username)
if user is None:
error_messages.append("用户名密码错误")
self.render("login.html", error_messages=error_messages, username=username)
return
if user["status"] == 0:
error_messages.append("帐户没有开通")
self.render("login.html", error_messages=error_messages, username=username)
return
password_generator = UserPassword()
password_hash = password_generator.generate_hash(password, user["password_salt"])
if password_hash != user["password_hash"]:
error_messages.append("用户名密码错误")
self.render("login.html", error_messages=error_messages, username=username)
return
session = Session(self.settings["session_secretSid"], self.settings["session_secretEid"], self.settings["session_expired"])
if session.encode(user["id"]) is False:
error_messages.append("用户数据错误")
self.render("login.html", error_messages=error_messages, username=username)
return
sid = session.getSid()
eid = session.getEid()
self.set_secure_cookie("sid", sid, None)
self.set_secure_cookie("eid", eid, None)
self.redirect(self.get_argument("next", "/"))
示例5: command_start
def command_start(bot, update):
chat_id = update.message.chat_id
if chat_id not in SESSIONS.keys():
messenger = Messenger(bot, logger)
SESSIONS[chat_id] = Session(chat_id, config_instance, logger)
SESSIONS[chat_id].set_messenger(messenger)
SESSIONS[chat_id].quiz = Quiz(SESSIONS[chat_id])
示例6: get
def get(self):
if 'pairing' in self.request.arguments:
key = self.get_argument('pairing')
# validate pairing key
if 'type' in self.request.arguments:
if 'session' in self.request.arguments:
session = Session.get(self.get_argument('session'))
if session:
if self.get_argument('type') == 'update':
self.writeout( session.get_update() )
elif self.get_argument('type') == 'function':
queries = self.get_argument('queries')
qargs = json.loads(queries)
args = [urllib.unquote(arg) for arg in qargs]
decoded = [decode_func_args(a) for a in args]
for fnargs in decoded:
self.writeout( session.handle_function(fnargs) )
return
else:
self.writeout( { 'no':'huh' } )
# validate session
#self.writeout( [ {'add': {'btapp':{'torrent':{'aotheu':{'hello':23}}}} } ] )
else:
self.set_status(404)
else:
#logging.info('no session id in args -- %s, %s' % (self.request.uri, self.request.arguments))
session = Session.create(Client.instances[0])
self.writeout( {'session':session.id} )
else:
self.writeout( { 'hey':'whatup' } )
else:
self.set_status(403)
示例7: killProcess
def killProcess(agent, user, password, pid):
s = Session(agent, service="ProcessStop")
s.authorize(user, password)
response = s.doRequest(attributes={"PID" : str(pid)})
return int(ElementTree.fromstring(response).get("ExitCode"))
示例8: get
def get(self):
username = self.request.get("user")
password = self.request.get("password")
self.response.headers['Content-Type'] = 'application/json; charset=utf-8'
if not username or not password:
# some fields were missing in the request
self.response.write(json_error('invalid', ''))
else:
# check if username exists in db
query_user = User.query(User.username == username).fetch()
if query_user:
# check if password is correct
query = User.query(ndb.AND(User.username == username, User.pswd == password)).fetch()
if query:
# generate 64 char session cookie and send it back
cookie = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for _ in range(64))
session = Session(cookie = cookie, user = username)
session.put()
self.response.write(login_response('ok', cookie))
else:
# password was incorrect
self.response.write(json_error('failure', 'password'))
else:
# user didn't exist
self.response.write(json_error('failure', 'user'))
示例9: on_finish
def on_finish(self):
try:
self.session.commit()
except Exception as e:
self.session.rollback()
import traceback
logging.critical('Transaction needed to be rolled back because of: \n %s' % traceback.format_exc() )
Session.remove()
示例10: __call__
def __call__(self, environ, start_response):
sc = SimpleCookie()
if 'HTTP_COOKIE' in environ:
sc.load(environ.get('HTTP_COOKIE'))
ses = Session(ExpressSession(sc))
ses.read()
environ['express.session'] = ses
return self.app(environ, start_response)
示例11: login
def login(self, password):
if self.password == password:
current_session = Session(player_id=self.player_id)
current_session.start_session()
self.sessions.append(current_session)
print("Player {} has logged in".format(self.name))
else:
print("Password error. Try again.")
示例12: query
def query(self, query_type, msg_body=None):
session = Session(self.peer.connect_str, service="Manager")
session.authorize(self.peer.domain.user, self.peer.domain.password)
pwd_response = session.doRequest(attributes={"Type": "GetDatabaseCredentials", "Database": self.database.name})
pwd_xml = ElementTree.fromstring(pwd_response)
pwd = pwd_xml.find("Password").text.strip()
return queryEngine(self.address, self.port, query_type, pwd, msg_body)
示例13: __init__
def __init__(self, host, port, service='SQL2'):
"""Constructor for the EncodedSession class."""
Session.__init__(self, host, port=port, service=service)
self.doConnect()
self.__output = None
self.__input = None
self.__inpos = 0
self.closed = False
示例14: execute
def execute(self, session: Session, args: Dict[str, Any]) -> ExitCode:
data_to_remove = get_data_to_remove(session)
data = args['data']
args['data'] = deque(filterfalse(lambda x: x == data_to_remove, data))
session.get_io().output('Removed {} data points'.format(len(data) - len(args['data'])))
return ExitCode.SUCCESS
示例15: get_data_points_per_line
def get_data_points_per_line(session: Session) -> int:
while True:
data_points_per_line = get_integer_from_user(session, 'How many data points per line should be outputted: ')
if data_points_per_line <= 0:
session.get_io().output('Your input must be greater than zero, instead got {}'.format(str(data_points_per_line)))
time.sleep(1)
session.clear()
continue
return data_points_per_line