def __request_comment__(comment_id): # comment_id is Tweet ID ret = session.getSession().get("https://mp.weixin.qq.com/misc/appmsgcomment?action=list_comment&begin=0&count=20&comment_id="+str(comment_id)+"&filtertype=0&day=0&type=2&max_id=0&token="+str(session.getUrlToken())+"&lang=zh_CN&f=json&ajax=1") # logger.logger.debug(ret.text) ret_json = ret.json() if not ret_json["base_resp"]["ret"] == 0: # Todo Exception Handling # :block this thread and wait login status back raise NotImplementedError() return json.loads(ret_json["comment_list"])
def POST(self): i = web.input() username = i.get('username') passwd = i.get('passwd') if (username, passwd) in allowed: session.getSession().logged_in = True web.setcookie('system_mangement', '', 60) raise web.seeother('/index') else: return '<h1>Login Error!!!</h1></br><a href="/login">Login</a>'
def __WaitForScan(config, qrCallback): _referer = "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=" + config[ "username_urlencode"] + "&token=" # First `ask for loginqrcode` Request Will Respond ret:1 with msg:default r = session.getSession().get( "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1", headers={"Referer": _referer}) logger.logger.debug(r.text) # Then Request QRCode Image r_img = session.getSession().get( "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=getqrcode¶m=4300&rd=36", headers={"Referer": _referer}) i = Image.open(BytesIO(r_img.content)) # Call `qrCallback` Async to inform you of scanning qrcode or you can customize your action threading.Thread(target=qrCallback, args=(i, )).start() # Check Scan Status while True: time.sleep(1.0) r = session.getSession().get( "https://mp.weixin.qq.com/cgi-bin/loginqrcode?action=ask&token=&lang=zh_CN&f=json&ajax=1", headers={"Referer": _referer}) logger.logger.debug(r.text) ret_status = r.json()["status"] # Response List: # {"base_resp":{"err_msg":"ok","ret":0},"status":0,"user_category":0} Not Scan # {"base_resp":{"err_msg":"ok","ret":0},"status":1,"user_category":3} Confirm Login # {"base_resp":{"err_msg":"ok","ret":0},"status":3,"user_category":3} Timeout # {"base_resp":{"err_msg":"ok","ret":0},"status":4,"user_category":0} Scanned if ret_status == 0: logger.logger.info("Waiting For Scan") elif ret_status == 4: logger.logger.info("Scanned!") elif ret_status == 1: logger.logger.info("Scan Confirmed!") return True elif ret_status == 3: logger.logger.error("Timeout in scanning qrCode") return False
def __request_message__(offset=0): ret = session.getSession().get( "https://mp.weixin.qq.com/cgi-bin/message?t=message/list&count=20&day=7&token=" + session.getUrlToken() + "&lang=zh_CN&f=json&offset=" + str(offset)) # logger.logger.debug(ret.text) # it's toooooooo big ret_json = ret.json() if not ret_json["base_resp"]["ret"] == 0: # Todo Exception Handling # :block this thread and wait login status back raise NotImplementedError() return ret.json()
def __request_comment_count__(count=5): ret = session.getSession().get("https://mp.weixin.qq.com/misc/appmsgcomment?action=get_unread_appmsg_comment&begin=0&count="+str(count)+"&token="+session.getUrlToken()+"&lang=zh_CN&f=json&ajax=1") # logger.logger.debug(ret.text) # it's toooooooo big ret_json = ret.json() if not ret_json["base_resp"]["ret"] == 0: # Todo Exception Handling # :block this thread and wait login status back raise NotImplementedError() count_dic = dict() for item in ret_json["item"]: count_dic[item["comment_id"]] = item["total_count"] return count_dic
def _checkLoggedIn(request): request.logged_in = False request.user = None request.session_id = None session_id = request.COOKIES.get(settings.SESSION_COOKIE_NAME, None) if session_id is not None: usession = session.getSession(session_id) if usession is not None: request.session = usession request.session_id = usession.id if session.USERNAME_KEY in request.session.keys(): username = request.session[session.USERNAME_KEY] if username is not None: user = models.getUserByName(username) if user is not None: request.logged_in = True request.user = user return request
def is_renwal_all(client, frame): data = json.loads(frame.body.decode())[0] insuranceType = data.get("insuranceType", [])[0] data['insuranceType'] = insuranceType client.send(body=json.dumps(data, ensure_ascii=False).encode(), destination=CJBX) companyId = data.get('companyId', []) # 货车暂时只做了人保的 如果是货车 或者挂车 只爬取人保 licenseType = data.get('licenseType', "02") # 保险公司选择 if len(companyId) == 0 or "2" in companyId: client.send(body=json.dumps(data, ensure_ascii=False).encode(), destination=EPICC) log.info('Got %s' % json.dumps(data, ensure_ascii=False)) sessiondt = "" sessiondt = getSession() requestcic = sessiondt['4'] loginRes = sessiondt['5'] pingansession = sessiondt['1'] ancheng_session = sessiondt['12'] hn_session = sessiondt['13'] plateNumber = data['plateNumber'] if len(plateNumber) != 7: log.error(u'plateNumber len != 7') return insureCarId = data['insureCarId'] sessionId = data['sessionId'] isPhone = data['isPhone'] insuranceType = data['insuranceType'] # insureTypeGroupId=data.get("insureTypeGroupId","9999") carInfo = 0 sql_carInfo = query_user_renewal(plateNumber) if sql_carInfo == 0: g1 = gevent.spawn(cic_entrance_renwal, requestcic, plateNumber) g2 = gevent.spawn(is_pingan_renwal, pingansession, plateNumber) g3 = gevent.spawn(is_ancheng_renewal, ancheng_session, plateNumber) gevent.joinall([g1, g2, g3]) cic_out = g1.value pingan_out = g2.value ancheng_out = g3.value if cic_out != 0 or pingan_out != 0 or ancheng_out != 0: if isinstance(cic_out, dict): carInfo = cic_out log.info(u"通过中华联合获取到续保信息") inser_user_renewal(carInfo) if isinstance(pingan_out, dict): carInfo = pingan_out log.info(u"通过平安获取到续保信息") inser_user_renewal(carInfo) if isinstance(ancheng_out, dict): carInfo = ancheng_out log.info(u"通过安诚获取到续保信息") inser_user_renewal(carInfo) # 通过行业协会进行查询 if carInfo == 0: carInfo = query_user_permium_time(plateNumber) if carInfo != 0: # log.info(carInfo) log.info(u"通过行业协会取到续保信息") carInfo['insuredAddress'] = "" carInfo['mobile'] = "" if cic_out == 0 and pingan_out == 0 and carInfo == 0: carInfo = query_user_renewal(plateNumber) if carInfo == 0: time.sleep(2) carInfo = query_user_renewal(plateNumber) # 通过行业协会进行查询 if carInfo == 0: carInfo = query_user_permium_time(plateNumber) if carInfo != 0: carInfo['insuredAddress'] = "" carInfo['mobile'] = "" if carInfo == 0: # 不是续保用户 # 添加队列 send_complete_flag(client, plateNumber, "0", isPhone, sessionId) log.info("plateNumber %s = 0" % plateNumber) else: carInfo = sql_carInfo # 如果是续保用户 if carInfo != 0: send_complete_flag(client, plateNumber, "1", isPhone, sessionId, carInfo) carInfo['4'] = requestcic carInfo['5'] = loginRes carInfo['1'] = sessiondt['1'] carInfo['12'] = sessiondt['12'] carInfo['13'] = sessiondt['13'] # 添加client carInfo['insureCarId'] = insureCarId carInfo['client'] = client carInfo['sessionId'] = sessionId carInfo['isPhone'] = isPhone carInfo['companyId'] = data.get('companyId', []) carInfo['insuranceType'] = insuranceType carInfo['licenseType'] = licenseType plateNo_getSource(carInfo)
''' Created on Jun 29, 2015 @author: lin ''' from vod_orm import * import session import sqlalchemy.exc session = session.getSession() newUser = User(name='tom', id=23) newVideo = Video(title = 'testvideo', id = 24) user = session.query(User).filter(User.id == '23').one() print '..' print user print '..' newVideo.user = newUser.id try: session.add(newUser) session.add(newVideo) res = session.query(Video).all() print res[0].title print newVideo session.commit() except sqlalchemy.exc.IntegrityError as detail: print type(detail)
def loadSession(): userSession = session.getSession('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiJmb28xMjMiLCJyb2xlIjoiY2xpZW50IiwiaWF0IjoxNTA4NTMwNTg2LCJleHAiOjE1MDg1MzE0ODZ9.0ydDCd5nRSdrWwfZSLXk3_zFBa9igkv9bmqok9l-GtU') return userSession
def __init__(self, parent, controller): ttk.Frame.__init__(self, parent) self.style = ttk.Style() self.style.configure('Treeview', rowheight=50) self.style.configure('My.TLabel', font=('Times', 8, 'bold'), justify='center', background='green', foreground='white') self.style.configure('My.TFrame', font=('Times', 8, 'bold'), justify='center', background='green') self.style.configure('Text.TLabel', font=('Times', 8, 'bold'), justify='center', background='green', foreground="white") self.style.configure('Mod.TLabelFrame.Label', font=('Times', 8, 'bold'), justify='center', background='green', foreground="white") self.style.configure('H1.TLabel', font=('Times', 12, 'bold'), justify='center', background='green', foreground="white") self.style.configure('Bt.TButton', font=('Times', 10, 'normal'), justify='center', background='green') self.lbl = ttk.Label(self, style="H1.TLabel", anchor=N, text='Orders List') self.lbl.pack(fill=BOTH) db = Database() cursor = db.conn.cursor() self.top = ttk.Frame(self, style="My.TFrame") self.bottom = ttk.Frame(self, style="My.TFrame") self.top.pack(side=TOP, fill=BOTH) self.bottom.pack(side=BOTTOM, fill=BOTH, expand=True) self.note = ttk.Label( self, anchor=N, text= "Note: DoubleClick Or Press EnterKey on the Order to see Order Details", style='My.TLabel') self.note.pack(fill=BOTH) if (sess.ifSessionExist(SESSION_DIR)): login_name = 'Login as:- ' + sess.getSession( SESSION_DIR, 'firstname') + ' ' + sess.getSession( SESSION_DIR, 'lastname') self.lbl = ttk.Label(self, style="Text.TLabel", text=login_name, font=CUSTOM_FONT) self.lbl.pack(in_=self.top, side=LEFT, padx=5, pady=5) self.btn = ttk.Button(self, style="Bt.TButton", text="Logout", command=lambda: self.logout(controller)) self.btn.pack(in_=self.top, side=RIGHT, padx=5, pady=5) self.btn_setting = ttk.Button(self, style="Bt.TButton", text="Setting", command=lambda: self.Setting(controller)) self.btn_setting.pack(in_=self.top, side=RIGHT, padx=5, pady=5) self.set_Col()
def Login(config, qrCallback, verifycodeCallback, verifycode=None, failCallback=None): if callable(qrCallback) is False: raise TypeError("parma `qrCallback` should be a function") if callable(verifycodeCallback) is False: raise TypeError("parma `verifycodeCallback` should be a function") global _isLogining if _isLogining: logger.logger.warning("Logining!") return False _isLogining = True # First Send Username And MD5(Password) r = session.getSession().post( "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=startlogin", data={ "username": config["username"], "pwd": config["password_md5"], "imgcode": "" if (verifycode is None) else verifycode, "f": "json", "userlang": "zh_CN", "redirect_url": "", "token": "", "lang": "zh_CN", "ajax": "1" }, headers={"Referer": "https://mp.weixin.qq.com/"}) logger.logger.debug(r.text) r_json = r.json() ret_code = r_json["base_resp"]["ret"] # Return 0 means your Username and Password is right # and you can go straight to the next step if ret_code == 0: logger.logger.info("Login First-Step Succeed") if __WaitForScan(config, qrCallback): logger.logger.info("Login Success!") r = session.getSession().post( "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=login", data={ "userlang": "zh_CN", "redirect_url": "", "token": "", "lang": "zh_CN", "f": "json", "ajax": "1" }, headers={ "Referer": "https://mp.weixin.qq.com/cgi-bin/bizlogin?action=validate&lang=zh_CN&account=" + config["username_urlencode"] + "&token=" }) logger.logger.debug(r.text) if r.json()["base_resp"]["ret"] != 0: logger.logger.critical("Login Third-Step Fail") _isLogining = False return False redirect_url = r.json()["redirect_url"] url_token = regex.compile("token=[0-9]*").findall( redirect_url)[0].replace("token=", "") logger.logger.info("Get Url_Token: " + url_token) session.setUrlToken(url_token) else: # Timeout in scanning qrcode session.clear() _isLogining = False return Login(config, qrCallback, verifycode, failCallback) _isLogining = False return True # Return 200008 OR 200027 means it need VerifyCode Or bad VerifyCode elif ret_code == 200008 or ret_code == 200027: logger.logger.warning("Need verify code or wrong verify code") ret = session.getSession().get( "https://mp.weixin.qq.com/cgi-bin/verifycode?username="******"username"] + "&r=1549177766480") vc_img = Image.open(BytesIO(ret.content)) _isLogining = False return Login(config, qrCallback, verifycodeCallback, verifycodeCallback(vc_img), failCallback) # Login Fail in First Step # Return 200023 means wrong Username or wrong Password elif ret_code == 200023: hint = "Cannot login because of wrong username or password. Please check your setting." logger.logger.critical(hint) if callable(failCallback): failCallback(hint) _isLogining = False return False else: hint = "Login First-Step Fail - " + str(r.json()["base_resp"]) logger.logger.critical(hint) if callable(failCallback): failCallback(hint) _isLogining = False return False