def lbAlert(): if request.method == 'POST': headers = request.headers data = request.data all = json.loads(data) # print all["Message"] message = json.loads(all["Message"]) # print message["AlarmName"] # print message["NewStateReason"] content = "AlarmName:\"" + str(message["AlarmName"]) + "\"" #从redis中读取weChat相关配置参数 weurl = redis_store.hget('wechat', 'weurl') weCorpid = redis_store.hget('wechat', 'weCorpid') weSecret = redis_store.hget('wechat', 'weSecret') wegroupids = redis_store.hget('wechat', 'wegroupids') #发微信 from app.utils.send import weChat wechat = weChat(weurl, weCorpid, weSecret) wechat.send_message(wegroupids, content) return "yes yes" else: return "no no"
def get_cookie(): one_time_code = request.form.get("one_time_code") valid = redis_store.get(one_time_code) if valid and redis_store.hget(valid, "uuid"): session["logged_in"] = True session["username"] = valid redis_store.set(valid + ":logged_in", True) return "successful login" return "failed"
def client_send_message_to_server(message): user_id = str(request.cookies.get('user_id')) friend_id = redis_store.hget('active_chat', user_id).decode('utf-8') room_id = '-'.join([friend_id, user_id]) message = Messages(body=message['data'], receiver=friend_id, sender=user_id) db.session.add(message) db.session.commit() emit('server_send_message_to_client', {'message': message.body}, room=room_id)
def clearcdn(urlstr, remote_ip, network): #从redis读取akamai相关配置参数 from app import redis_store #weurl = redis_store.hget('wechat','weurl') #akamaiusername = redis_store.hget('akamai','username') #akamaipassword = redis_store.hget('akamai','password') apiurl = redis_store.hget('akamaiv3', 'apiurl') #执行akamai clear cdn cache headers = {'content-type': 'application/json'} data = '{"clean_url":"%s","network":"%s"}' % (urlstr, network) r = requests.post(apiurl, data=data, headers=headers) logs("url " + urlstr + str(r) + remote_ip) return r.json()
def login(): if current_user.is_authenticated: return redirect(url_for('main.index')) form = LoginForm() # заполняем SelectField пользователями сайта choices = [(key, redis_store.hgetall(key)['username']) for key in redis_store.hkeys('site_users')] if len(choices) > 0: form.username.choices = choices if form.validate_on_submit(): user = redis_store.exists(form.username.data) password_hash = '' if redis_store.hget( form.username.data, 'password_hash') == None else redis_store.hget( form.username.data, 'password_hash') if not user or not check_password_hash(password_hash, form.password.data): flash('Неверный логин или пароль!') return redirect(url_for('auth.login')) user_data = redis_store.hgetall(form.username.data) user_id = form.username.data username = user_data['username'] # email = user_data['email'] password_hash = user_data['password_hash'] operating_mode = user_data['operating_mode'] role = user_data['role'] user = User(user_id=user_id, username=username, password_hash=password_hash, operating_mode=operating_mode, role=role) login_user(user) next_page = request.args.get('next') if not next_page or url_parse(next_page).netloc != '': next_page = url_for('main.index') return redirect(next_page) return render_template('auth/login.html', form=form)
def get_headline(faculty, page=1): news_list = [] for name in config.ORIGIN_TYPE: if name != 'xb': key = str(page) else: key = faculty + '_' + str(page) data = redis_store.hget(name, key) if data: data = ast.literal_eval(bytes.decode(data)) for content in data: news_list.append(content) news_list.sort(key=lambda element: element['time'], reverse=True) if page == '1': xm_news = xm.get_list(page) if xm_news: xm_news.reverse() for data in xm_news: if data: news_list.insert(0, data) return news_list
def fenYeSearch(request, fenyeno, hashname, searchstr): #根据searchstr查询出所有key allkeys = [] for key in redis_store.hkeys(hashname): if searchstr in key: allkeys.append(key) #求搜索相关的所有keys的个数 allCounts = len(allkeys) #求出相关的所有key和value all = {} for k in allkeys: all[k] = redis_store.hget(hashname, k) try: curPage = int(request.args.get('curPage', '1')) allPage = int(request.args.get('allPage', '1')) pageType = str(request.args.get('pageType', '')) except ValueError: curPage = 1 allPage = 1 pageType = '' if pageType == 'pageDown': curPage += 1 elif pageType == 'pageUp': curPage -= 1 startPos = (curPage - 1) * fenyeno endPos = startPos + fenyeno posts = allkeys[startPos:endPos] if curPage == 1 and allPage == 1: allPage = allCounts / fenyeno remainPost = allCounts % fenyeno if remainPost > 0: allPage += 1 return posts, allPage, curPage, allCounts, all
class User(): username = redis_store.hget('user','username') password = redis_store.hget('user','password')
def decorated_function(*args, **kwargs): username = redis_store.hget('user','username') if username != session.get('username'): return redirect(url_for('login')) return f(*args, **kwargs)
def clearnginx(urlstr, remote_ip): hostname = urlparse(urlstr).hostname if hostname is None: message = "%s is not a valid url" % urlstr result = {'status': 'error', 'message': message} logs(message + " " + remote_ip) return result #获取url后缀 schemelen = len(urlparse(urlstr).scheme) hostnamelen = len(hostname) urlpath = urlstr[schemelen + hostnamelen + 3:] if urlpath == '': urlpath = '/' #判断domain是否在配置文件中 try: from app import redis_store #从redis取的对应域名的ip ips = redis_store.hget("nginxip", hostname).split(',') if ips is None: message = "url %s hostname %s Not nginx cached" % (urlstr, hostname) result = {'status': 'error', 'message': message} logs(message + " " + remote_ip) return result except Exception: message = "url %s hostname %s Not nginx cached" % (urlstr, hostname) result = {'status': 'error', 'message': message} logs(message + " " + remote_ip) return result message = "" #判断对应的ip80端口是否还在启用状态 from app.utils.verify import verify_ip ips80 = [] for ip80 in ips: if verify_ip(ip80) is True: ips80.append(ip80) #执行nginx purge cache for ip in ips80: headers = {'host': hostname} purgeurl = "http://" + ip + "/purge" + urlpath rhtml = requests.get(purgeurl, headers=headers, timeout=15) httpStatus = str(rhtml.status_code) soup = BeautifulSoup( str(rhtml.text).replace("\r\n", ""), "html.parser") if httpStatus == '404': key = "no key" path = "no path" title = "404" else: key = str(soup.find_all(text=re.compile("Key"))) path = str(soup.find_all(text=re.compile("Path"))) title = str(soup.title) message += " nginx_ip : %s ,httpStatus : %s ,title : %s ,key : %s ,path : %s " % ( ip, httpStatus, title, key, path) result = {'status': 'success', 'message': message} logs("url " + urlstr + message + " " + remote_ip) return result
def house_list(): """ 首页搜索房屋 :return: """ # 获取所有的参数 args = request.args area_id = args.get('aid', '') start_date_str = args.get('sd', '') end_date_str = args.get('ed', '') # booking(订单量), price-inc(低到高), price-des(高到低), sort_key = args.get('sk', 'new') page = args.get('p', '1') # 打印参数 print("area_id=%s,sd=%s,ed=%s,sk=%s,page=%s" % (area_id, start_date_str, end_date_str, sort_key, page)) # 参数校验 try: page = int(page) except Exception as e: logging.error(e) return jsonify(errno=RET.PARAMERR, errmsg='参数错误') # 对日期进行相关处理 try: start_date = None end_date = None if start_date_str: start_date = datetime.datetime.strptime(start_date_str, '%Y-%m-%d') if end_date_str: end_date = datetime.datetime.strptime(end_date_str, '%Y-%m-%d') # 如果开始时间大于或者等于结束时间,就报错 print(start_date) print(end_date) if start_date and end_date: assert start_date < end_date, Exception('开始时间大于结束时间') except Exception as e: logging.error(e) return jsonify(errno=RET.PARAMERR, errmsg='日期错误') # 尝试从缓存获取 try: redis_key = "houses_%s_%s_%s_%s" % (area_id, start_date_str, end_date_str, sort_key) response_data = redis_store.hget(redis_key, page) if response_data: logging.info('load data from redis') return jsonify(errno=RET.OK, errmsg='获取成功', data=eval(response_data)) except Exception as e: logging.error(e) # 如果区域id存在 filters = [] if area_id: filters.append(House.area_id == area_id) # 定义数组保存冲突的订单 conflict_order = None if start_date and end_date: # 如果订单的开始时间 < 结束时间 and 订单的结束时间 > 开始时间 conflict_order = Order.query.filter(Order.begin_date < end_date, Order.end_date > start_date) elif start_date: # 订单的结束时间 > 开始时间 conflict_order = Order.query.filter(Order.end_date > start_date) elif end_date: # 订单的开始时间 < 结束时间 conflict_order = Order.query.filter(Order.begin_date < end_date) if conflict_order: # 取到冲突订单的房屋id conflict_house_id = [order.house_id for order in conflict_order] # 添加条件:查询出来的房屋不包括冲突订单中的房屋id filters.append(House.id.notin_(conflict_house_id)) # 查询数据 # houses_list = House.query.all() if sort_key == "booking": # 订单量从高到低 houses_query = House.query.filter(*filters).order_by( House.order_count.desc()) elif sort_key == "price-inc": # 价格从低到高 houses_query = House.query.filter(*filters).order_by(House.price.asc()) elif sort_key == "price-des": # 价格从高到低 houses_query = House.query.filter(*filters).order_by( House.price.desc()) else: # 默认以最新的排序 houses_query = House.query.filter(*filters).order_by( House.create_time.desc()) # 使用paginate进行分页 house_pages = houses_query.paginate(page, constants.HOUSE_LIST_PAGE_CAPACITY, False) # 获取当前页对象 houses_list = house_pages.items # 获取总页数 total_page = house_pages.pages # 将查询结果转成字符串 houses_dict = [] for house_each in houses_list: houses_dict.append(house_each.to_basic_dict()) # 提示 response_data 用于缓存 response_data = {"total_page": total_page, "houses": houses_dict} # 如果当前page小于总页数,则表明有数据 if page <= total_page: try: # 生成缓存用的key redis_key = "houses_%s_%s_%s_%s" % (area_id, start_date_str, end_date_str, sort_key) # 获取 redis_store 的 pipeline 对象,其可以一次可以做多个redis操作 pipe = redis_store.pipeline() # 开启事务 pipe.multi() # 缓存数据 pipe.hset(redis_key, page, response_data) # 设置保存数据的有效期 pipe.expire(redis_key, constants.HOUSE_LIST_REDIS_EXPIRES) # 提交事务 pipe.execute() except Exception as e: logging.error(e) # return jsonify(errno=RET.OK, errmsg='请求成功', data={"total_page": 1, "houses": houses_dict}) return jsonify(errno=RET.OK, errmsg='请求成功', data={ "total_page": total_page, "houses": houses_dict })
def wrapper(*args, **kwargs): args_data = [data for data in args] #args_data = ['origin','faculty','page','force_reload'] ''' 若是获取LIST,参数为 origin,faculty,page,force_reload 若是获取DETAIL,参数为 url,request_type ''' if storage_type == 'list': # 缓存新闻列表 name = args_data[0] # origin if name in ['xy', 'jw']: # 将xy,jw与xb区分,方便进行缓存 key = args_data[2] # page else: key = "%s_%s" % (args_data[1], args_data[2]) # faculty_page data = redis_store.hget(name, key) if args_data[3]: data = func(*args, **kwargs) redis_store.hset(name, key, str(data)) redis_store.expire(name, 2592000) # 缓存过期时间为30天 elif data: data = ast.literal_eval(bytes.decode(data)) redis_store.expire(name, 2592000) return data else: return {} ''' else: data = func(*args, **kwargs) redis_store.hset(name, key, str(data)) redis_store.expire(name, 2592000) # 缓存过期时间为30天 ''' elif storage_type == 'detail': # 缓存新闻详细 url = args[0] list_length = len(args) # url result_1 = re.search('http://(.*?)/', url) # 用于判断是是否是教务处新闻详细 if result_1.group(1) == 'www.gdust.cn': result_2 = re.search('(\d{8})\/(\d{1,4})', url) kw = result_2.group(1) + result_2.group(2) else: kw = re.search('\&id\=(\d{1,3})', url).group(1) data = redis_store.get(kw) if args[1]: data = func(*args, **kwargs) redis_store.set(kw, str(data)) redis_store.expire(kw, 2592000) elif data: data = ast.literal_eval(bytes.decode(data)) redis_store.expire(kw, 2592000) return data else: return {} ''' else: data = func(*args, **kwargs) redis_store.set(kw, str(data)) redis_store.expire(kw, 2592000) ''' return data