def validate_message(message): result = { 'message_type': None, 'status': 200, 'message': None, 'error_msg': None, } # 请求必须是JSON格式字符串 try: result['message'] = tool.json_load(message) print "result['message']:", result['message'] except Exception: result['message'] = message result['status'] = 400 result['error_msg'] = 'Request body Must be in `JSON` format' else: if not result['message'].get('message_type'): result['status'] = 403 result['error_msg'] = '`message_type` cannot be none' # 请求的 message_type 必须存在 elif not MESSAGE_TYPE.get(result['message']['message_type']): result['status'] = 404 result['error_msg'] = MESSAGE_TYPE[None]( '404: You know what it means') else: result['message_type'] = result['message']['message_type'] return result
def validate_post_request(self): result = { "status": 200, "body_json": None, "error_msg": None, } # 请求必须是JSON格式字符串 if re.match(r"^application/json[;]?(\s*charset=UTF-8)?$", self.request.headers.get("Content-Type"), re.I) is None: result["status"] = 400 result[ "error_msg"] = "`Content-Type` Must be `application/json; charset=UTF-8`" else: try: result["body_json"] = tool.json_load(self.request.body) except: result["status"] = 400 result["error_msg"] = "Request body Must be in `JSON` format" return result # 请求的URL必须存在 if POST_URL_RULES.get(self.request.uri) is None: result["status"] = 404 result["error_msg"] = POST_URL_RULES[None]( "404: You know what it means") return result
def get_promote_info(info): # 获取价格以及 促销 & 券 & 礼物 promote_api_url = PROMOTE_URL % ( MY_AREA[0], MY_AREA[1], MY_AREA[2], info["itemid"], info["分类id"], int(time.time() * 1000), ) # 获取页面html内容 if not DEBUG: response = yield tool.http_request({ "url": promote_api_url, "method": "GET", "headers": HEADERS }) open("kaola.promopt_page.html", "w").write(tool.try_decode_html_content(response.body)) item_content = open("kaola.promopt_page.html", "r").read() item_content = tool.json_load(item_content) # 这两个不是一模一样的吗 skuPrice = item_content["data"].get( "skuPrice") or item_content["data"]["skuDetailList"][0]["skuPrice"] min_price = min(skuPrice["currentPrice"], skuPrice["kaolaPrice"], skuPrice["suggestPrice"], skuPrice["marketPrice"]) presale = item_content["data"].get( "depositGoodsAdditionalInfo" ) or item_content["data"]["skuDetailList"][0]["depositSkuAdditionalInfo"] if presale: min_price = presale.get("handPrice") or min_price current_store = item_content["data"].get( "goodsCurrentStore" ) or item_content["data"]["skuDetailList"][0]["skuStore"]["currentStore"] promotion_info = item_content["data"].get("promotionList") or item_content[ "data"]["skuDetailList"][0]["promotionList"] or [] promote = [[x["promotionContent"], x["promotionUrl"], "0000 ~ 0000"] for x in promotion_info] quan = item_content["data"].get("goodsCouponList") or [] # q.d() return { "min_price": min_price, "current_store": current_store, "promote": promote, "quan": quan, "presale": bool(presale), }
def query(self, req_data): # print "query req_data:", req_data note_detail = yield self.user.record.query(_id=req_data["id"]) content = tool.json_load(note_detail["content"]) note_detail["content"] = content["content"] note_detail["width"] = content["width"] note_detail["height"] = content["height"] raise tornado.gen.Return(note_detail)
def on_message(self, message): logging.info("got message %r", message) message_json = tool.json_load(message) res_data = None try: func = self.__class__.routers.get(message_json.get("type")) if func: result = yield func(self, message_json["data"]) res_data = {"type": "init", "desc": "success", "data": result} else: res_data = { "code": 404, "desc": "No message type %s " % message_json.get("type"), "data": message } except Exception as e: res_data = {"code": 500, "desc": str(e), "data": None} self.write_message(res_data)
def on_message(self, message): print "on_message:", type(message), message try: if message is None: self.conf["db_wechai"]["any_message"].insert_one({ "bg-ts": time.time(), "errno": 1, "type": "connection-closed" }) self.on_connection_close("detected.") else: try: json_message = tool.json_load(message) assert isinstance(json_message.get("data"), dict) except Exception: json_message = { "errno": 2, "type": "message", "text": message, "data": {}, } json_message["bg-ts"] = time.time() try: yield self.conf["db_wechai"]["any_message"].insert_one( json_message) except Exception: print traceback.format_exc() return # do nothing (two ai will dead lock this produring message) try: if json_message["data"].get("self") is False: message_type = json_message["data"].get( "room") and "room-message" or "message" to_id = json_message["data"].get( "room") or json_message["data"]["from"] res_message = { "type": message_type, "to_id": to_id, "text": "%s (%s) said %s at %s" % (json_message["data"].get("from_nick"), json_message["data"]["from"], json_message["data"]["text"], json_message["data"]["date"]), } print "res_message:", res_message self.conf["ws_conn"].write_message( tool.json_stringify(res_message)) except Exception: print traceback.format_exc() except Exception: print traceback.format_exc()
def get_base_info(item): # 获取页面html内容 if not DEBUG: response = yield tool.http_request({ "url": item["url"], "method": "GET", "headers": HEADERS }) open("yanxuan.base_url_page.html", "w").write(tool.try_decode_html_content(response.body)) item_content = open("yanxuan.base_url_page.html", "r").read() item_content_lines = item_content.split("\n") icat = next( (i for (i, x) in enumerate(item_content_lines) if "\"item\":" in x), -1) info_text = item_content_lines[icat][7:-1] info_json = tool.json_load(info_text) # info_text = info_text.replace("\"item\":", "") # if info_text[-1] == ",": # info_text = info_text[0:-1] if item.get("iid"): item_info = next( (x for x in info_json["skuList"] if x["id"] == item["iid"]), {}) else: item_info = info_json["skuList"][item["index"]] if not item_info: return None promote_info = item_info.get("hdrkDetailVOList") if item_info.get("couponShortNameList"): quan_info = item_info.get("couponShortNameList") elif item_info.get("shortCouponList"): quan_info = [x["displayName"] for x in item_info["shortCouponList"]] else: quan_info = None price = min(item_info["retailPrice"], item_info["counterPrice"], item_info["calcPrice"], item_info["preSellPrice"]) if item_info.get("spmcBanner"): spmc_price = float(item_info["spmcBanner"].get("spmcPrice") or 0) price = spmc_price > 0 and min(spmc_price, price) or price if item_info.get("detailPromBanner"): activity_price = float( item_info["detailPromBanner"].get("activityPrice") or 0) price = activity_price > 0 and min(activity_price, price) or price info = { "name": item_info["skuTitle"], "iid": item_info["id"], "promote": [[x["name"], x["huodongUrlPc"], "0 ~ 0"] for x in promote_info], "quan": quan_info, "price": price, "store": item_info["sellVolume"], } return info