Flask愛家租房--房屋管理(搜索房屋列表)

文章目錄

    • 0.效果展示
    • 1.后端接口
    • 2.前端js
    • 3.前端html

0.效果展示

在這里插入圖片描述
在這里插入圖片描述

1.后端接口

house.py部分接口:

# GET /api/v1.0/houses?sd=2017-12-01&ed=2017-12-31&aid=10&sk=new&p=1
@api.route("/houses")
def get_house_list():"""獲取房屋的列表信息(搜索頁面)"""start_date = request.args.get("sd", "")  # 用戶想要的起始時間end_date = request.args.get("ed", "")  # 用戶想要的結束時間area_id = request.args.get("aid", "")  # 區域編號sort_key = request.args.get("sk", "new")  # 排序關鍵字page = request.args.get("p")  # 頁數# 處理時間try:if start_date:start_date = datetime.strptime(start_date, "%Y-%m-%d")if end_date:end_date = datetime.strptime(end_date, "%Y-%m-%d")if start_date and end_date:assert start_date <= end_dateexcept Exception as e:current_app.logger.error(e)return jsonify(errno=RET.PARAMERR, errmsg="日期參數有誤")# 判斷區域idif area_id:try:area = Area.query.get(area_id)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.PARAMERR, errmsg="區域參數有誤")# 處理頁數try:page = int(page)except Exception as e:current_app.logger.error(e)page = 1# 獲取緩存數據redis_key = "house_%s_%s_%s_%s" % (start_date, end_date, area_id, sort_key)try:resp_json = redis_store.hget(redis_key, page)except Exception as e:current_app.logger.error(e)else:if resp_json:return resp_json, 200, {"Content-Type": "application/json"}# 過濾條件的參數列表容器filter_params = []# 填充過濾參數# 時間條件conflict_orders = Nonetry:if start_date and end_date:# 查詢沖突的訂單conflict_orders = Order.query.filter(Order.begin_date <= end_date, Order.end_date >= start_date).all()elif start_date:conflict_orders = Order.query.filter(Order.end_date >= start_date).all()elif end_date:conflict_orders = Order.query.filter(Order.begin_date <= end_date).all()except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="數據庫異常")if conflict_orders:# 從訂單中獲取沖突的房屋idconflict_house_ids = [order.house_id for order in conflict_orders]# 如果沖突的房屋id不為空,向查詢參數中添加條件if conflict_house_ids:filter_params.append(House.id.notin_(conflict_house_ids))# 區域條件if area_id:filter_params.append(House.area_id == area_id)# 查詢數據庫# 補充排序條件if sort_key == "booking":  # 入住做多house_query = House.query.filter(*filter_params).order_by(House.order_count.desc())elif sort_key == "price-inc":house_query = House.query.filter(*filter_params).order_by(House.price.asc())elif sort_key == "price-des":house_query = House.query.filter(*filter_params).order_by(House.price.desc())else:  # 新舊house_query = House.query.filter(*filter_params).order_by(House.create_time.desc())# 處理分頁try:#                               當前頁數          每頁數據量                              自動的錯誤輸出page_obj = house_query.paginate(page=page, per_page=constants.HOUSE_LIST_PAGE_CAPACITY, error_out=False)except Exception as e:current_app.logger.error(e)return jsonify(errno=RET.DBERR, errmsg="數據庫異常")# 獲取頁面數據house_li = page_obj.itemshouses = []for house in house_li:houses.append(house.to_basic_dict())# 獲取總頁數total_page = page_obj.pagesresp_dict = dict(errno=RET.OK, errmsg="OK", data={"total_page": total_page, "houses": houses, "current_page": page})resp_json = json.dumps(resp_dict)if page <= total_page:# 設置緩存數據redis_key = "house_%s_%s_%s_%s" % (start_date, end_date, area_id, sort_key)# 哈希類型try:# redis_store.hset(redis_key, page, resp_json)# redis_store.expire(redis_key, constants.HOUES_LIST_PAGE_REDIS_CACHE_EXPIRES)# 創建redis管道對象,可以一次執行多個語句pipeline = redis_store.pipeline()# 開啟多個語句的記錄pipeline.multi()pipeline.hset(redis_key, page, resp_json)pipeline.expire(redis_key, constants.HOUES_LIST_PAGE_REDIS_CACHE_EXPIRES)# 執行語句pipeline.execute()except Exception as e:current_app.logger.error(e)return resp_json, 200, {"Content-Type": "application/json"}

2.前端js

search.js

var cur_page = 1; // 當前頁
var next_page = 1; // 下一頁
var total_page = 1;  // 總頁數
var house_data_querying = true;   // 是否正在向后臺獲取數據// 解析url中的查詢字符串
function decodeQuery(){var search = decodeURI(document.location.search);return search.replace(/(^\?)/, '').split('&').reduce(function(result, item){values = item.split('=');result[values[0]] = values[1];return result;}, {});
}// 更新用戶點選的篩選條件
function updateFilterDateDisplay() {var startDate = $("#start-date").val();var endDate = $("#end-date").val();var $filterDateTitle = $(".filter-title-bar>.filter-title").eq(0).children("span").eq(0);if (startDate) {var text = startDate.substr(5) + "/" + endDate.substr(5);$filterDateTitle.html(text);} else {$filterDateTitle.html("入住日期");}
}// 更新房源列表信息
// action表示從后端請求的數據在前端的展示方式
// 默認采用追加方式
// action=renew 代表頁面數據清空從新展示
function updateHouseData(action) {var areaId = $(".filter-area>li.active").attr("area-id");if (undefined == areaId) areaId = "";var startDate = $("#start-date").val();var endDate = $("#end-date").val();var sortKey = $(".filter-sort>li.active").attr("sort-key");var params = {aid:areaId,sd:startDate,ed:endDate,sk:sortKey,p:next_page};$.get("/api/v1.0/houses", params, function(resp){house_data_querying = false;if ("0" == resp.errno) {if (0 == resp.data.total_page) {$(".house-list").html("暫時沒有符合您查詢的房屋信息。");} else {total_page = resp.data.total_page;if ("renew" == action) {cur_page = 1;$(".house-list").html(template("house-list-tmpl", {houses:resp.data.houses}));} else {cur_page = next_page;$(".house-list").append(template("house-list-tmpl", {houses: resp.data.houses}));}}}})
}$(document).ready(function(){var queryData = decodeQuery();var startDate = queryData["sd"];var endDate = queryData["ed"];$("#start-date").val(startDate);$("#end-date").val(endDate);updateFilterDateDisplay();var areaName = queryData["aname"];if (!areaName) areaName = "位置區域";$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html(areaName);// 獲取篩選條件中的城市區域信息$.get("/api/v1.0/areas", function(data){if ("0" == data.errno) {// 用戶從首頁跳轉到這個搜索頁面時可能選擇了城區,所以嘗試從url的查詢字符串參數中提取用戶選擇的城區var areaId = queryData["aid"];// 如果提取到了城區id的數據if (areaId) {// 遍歷從后端獲取到的城區信息,添加到頁面中for (var i=0; i<data.data.length; i++) {// 對于從url查詢字符串參數中拿到的城區,在頁面中做高亮展示// 后端獲取到城區id是整型,從url參數中獲取到的是字符串類型,所以將url參數中獲取到的轉換為整型,再進行對比areaId = parseInt(areaId);if (data.data[i].aid == areaId) {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'" class="active">'+ data.data[i].aname+'</li>');} else {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'">'+ data.data[i].aname+'</li>');}}} else {// 如果url參數中沒有城區信息,不需要做額外處理,直接遍歷展示到頁面中for (var i=0; i<data.data.length; i++) {$(".filter-area").append('<li area-id="'+ data.data[i].aid+'">'+ data.data[i].aname+'</li>');}}// 在頁面添加好城區選項信息后,更新展示房屋列表信息updateHouseData("renew");// 獲取頁面顯示窗口的高度var windowHeight = $(window).height();// 為窗口的滾動添加事件函數window.onscroll=function(){// var a = document.documentElement.scrollTop==0? document.body.clientHeight : document.documentElement.clientHeight;var b = document.documentElement.scrollTop==0? document.body.scrollTop : document.documentElement.scrollTop;var c = document.documentElement.scrollTop==0? document.body.scrollHeight : document.documentElement.scrollHeight;// 如果滾動到接近窗口底部if(c-b<windowHeight+50){// 如果沒有正在向后端發送查詢房屋列表信息的請求if (!house_data_querying) {// 將正在向后端查詢房屋列表信息的標志設置為真,house_data_querying = true;// 如果當前頁面數還沒到達總頁數if(cur_page < total_page) {// 將要查詢的頁數設置為當前頁數加1next_page = cur_page + 1;// 向后端發送請求,查詢下一頁房屋數據updateHouseData();} else {house_data_querying = false;}}}}}});$(".input-daterange").datepicker({format: "yyyy-mm-dd",startDate: "today",language: "zh-CN",autoclose: true});var $filterItem = $(".filter-item-bar>.filter-item");$(".filter-title-bar").on("click", ".filter-title", function(e){var index = $(this).index();if (!$filterItem.eq(index).hasClass("active")) {$(this).children("span").children("i").removeClass("fa-angle-down").addClass("fa-angle-up");$(this).siblings(".filter-title").children("span").children("i").removeClass("fa-angle-up").addClass("fa-angle-down");$filterItem.eq(index).addClass("active").siblings(".filter-item").removeClass("active");$(".display-mask").show();} else {$(this).children("span").children("i").removeClass("fa-angle-up").addClass("fa-angle-down");$filterItem.eq(index).removeClass('active');$(".display-mask").hide();updateFilterDateDisplay();}});$(".display-mask").on("click", function(e) {$(this).hide();$filterItem.removeClass('active');updateFilterDateDisplay();cur_page = 1;next_page = 1;total_page = 1;updateHouseData("renew");});$(".filter-item-bar>.filter-area").on("click", "li", function(e) {if (!$(this).hasClass("active")) {$(this).addClass("active");$(this).siblings("li").removeClass("active");$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html($(this).html());} else {$(this).removeClass("active");$(".filter-title-bar>.filter-title").eq(1).children("span").eq(0).html("位置區域");}});$(".filter-item-bar>.filter-sort").on("click", "li", function(e) {if (!$(this).hasClass("active")) {$(this).addClass("active");$(this).siblings("li").removeClass("active");$(".filter-title-bar>.filter-title").eq(2).children("span").eq(0).html($(this).html());}})
})

3.前端html

search.html

<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><title>愛家-房源</title><link href="/static/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet"><link href="/static/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet"><link href="/static/css/reset.css" rel="stylesheet"><link href="/static/plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css" rel="stylesheet"><link href="/static/css/ihome/main.css" rel="stylesheet"><link href="/static/css/ihome/search.css" rel="stylesheet">
</head>
<body><div class="container"><div class="top-bar"><div class="nav-bar"><h3 class="page-title">房 源</h3><a class="nav-btn fl" href="/"><span><i class="fa fa-angle-left fa-2x"></i></span></a></div><ul class="filter-title-bar"><li class="filter-title"><span>入住日期</span><span><i class="fa fa-angle-down"></i></span><span class="split-line fr">|</span></li><li class="filter-title"><span>位置區域</span><span><i class="fa fa-angle-down"></i></span><span class="split-line fr">|</span></li><li class="filter-title"><span>最新上線</span><span><i class="fa fa-angle-down"></i></span></li></ul><div class="filter-item-bar"><div class="filter-item filter-date"><div class="input-daterange input-group"><input type="text" class="input-sm form-control" id="start-date" /><span class="input-group-addon"></span><input type="text" class="input-sm form-control" id="end-date" /></div></div><ul class="filter-item filter-area"></ul><ul class="filter-item filter-sort"><li class="active" sort-key="new">最新上線</li><li sort-key="booking">入住最多</li><li sort-key="price-inc">價格 低-</li><li sort-key="price-des">價格 高-</li></ul></div></div><div class="display-mask"></div><ul class="house-list"></ul><script id="house-list-tmpl" type="text/html">{{each houses as house}}<li class="house-item"><a href="/detail.html?id={{house.house_id}}"><img src="{{house.img_url}}"></a><div class="house-desc"><div class="landlord-pic"><img src="{{house.user_avatar}}"></div><div class="house-price"><span>{{(house.price/100.0).toFixed(0)}}</span>/</div><div class="house-intro"><span class="house-title">{{house.title}}</span><em>出租{{house.room_count}}- {{house.order_count}}次入住 - {{house.address}}</em></div></div></li>{{/each}}</script><div class="footer"><p><span><i class="fa fa-copyright"></i></span>愛家租房&nbsp;&nbsp;享受家的溫馨</p></div></div><script src="/static/js/jquery.min.js"></script><script src="/static/plugins/bootstrap/js/bootstrap.min.js"></script><script src="/static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js"></script><script src="/static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script><script src="/static/js/template.js"></script><script src="/static/js/ihome/search.js"></script>
</body>
</html>

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/452551.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/452551.shtml
英文地址,請注明出處:http://en.pswp.cn/news/452551.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

c語言用if語句判斷字符類型,C語言if語句的使用

C語言if語句的使用【例3】#includeint main(void){char c;printf("input a character: ");cgetchar();if(c<32)printf("This is a control character\n");else if(c>0&&c<9)printf("This is a digit\n");else if(c>A&&a…

SQL的特點

1.綜合統一集數據定義語言&#xff08;DDL&#xff09;&#xff0c;數據操縱語言&#xff08;DML&#xff09;&#xff0c;數據控制語言&#xff08;DCL&#xff09;功能于一體。可以獨立完成數據庫生命周期中的全部活動&#xff1a;定義和修改、刪除關系模式&#xff0c;定義和…

編程語言API性能大比拼

Ciaran是Skimlinks項目團隊中的一名領導者&#xff0c;熱愛開發&#xff0c;在業余時間喜歡研究一門新語言。作者和他的團隊在開發Skimlinks項目時遇到了一些困難&#xff0c;于是做了這份測試&#xff0c;文中將Node.js、Scala、Go、Python、PHP進行對比&#xff0c;最終Pytho…

ubuntu 安裝ssh服務

1&#xff1a;安裝 $ sudo apt-get install openssh-server 2&#xff1a;檢查ssh服務開啟狀態 $ ps -s | grep ssh 3&#xff1a;啟動ssh服務 $ service ssh start 4&#xff1a;本地登錄 $ ssh localhost轉載于:https://www.cnblogs.com/andy1327/p/9089930.html

手把手0基礎項目實戰(一)——教你搭建一套可自動化構建的微服務框架(SpringBoot+Dubbo+Docker+Jenkins)...

本文你將學到什么&#xff1f; 本文將以原理實戰的方式&#xff0c;首先對“微服務”相關的概念進行知識點掃盲&#xff0c;然后開始手把手教你搭建這一整套的微服務系統。 項目完整源碼下載 https://github.com/bz51/SpringBoot-Dubbo-Docker-Jenkins 這套微服務框架能干啥&am…

C語言中臨時變量寫在哪里,C語言中不允許創建臨時變量,交換兩個數的內容

在C語言中可以通過建立臨時變量來實現兩個變量的交換&#xff0c;當不允許建立臨時變量時&#xff0c;應該怎樣實現兩變量的交換呢&#xff1f;假設有兩個變量num1和num2&#xff1b;下面通過兩種方法進行分析。方法一&#xff1a;利用加減法。具體算法分析如下&#xff1a;由于…

Python面試題總結(8)--操作類

1. 請寫一個 Python 邏輯&#xff0c;計算一個文件中的大寫字母數量 答&#xff1a;讀取‘A.txt’中的大寫字母數量 with open(A.txt) as f:"""計算一個文件中的大寫字母數量"""count 0for i in f.read():if i.isupper():count 1 print(cou…

聯合主鍵

一個數據庫表只能有一個主鍵&#xff0c;不允許兩個主鍵。但是允許兩個字段聯合起來設置為主鍵&#xff0c;這叫聯合主鍵。

node之post提交上傳

post文件上傳 multer 中間件 在node中 express為了性能考慮采用按需加載的方式&#xff0c;引入各種中間件來完成需求&#xff0c; 平時解析post上傳數據時候&#xff0c;是用body-parse。但這個中間件有缺點&#xff0c;只能解析post的文本內容&#xff0c;&#xff08;applic…

要有自己的核心競爭力,應對時代變遷

在之前的PC時代和互聯網時代&#xff0c;人們都有一些顧慮&#xff0c;覺得智能化新技術的到來和采用將會導致就業人數急劇減少。 但實際上&#xff0c;無論是PC還是互聯網這樣新技術的到來&#xff0c;其實都對就業有極大的促進作用&#xff0c;其中最明顯的例子&#xff0c;…

ul、li列表簡單實用代碼實例

利用ul和li可以實現列表效果&#xff0c;下面就是一個簡單的演示。 代碼如下: 010203040506070809101112131415161718192021222324252627282930313233<!DOCTYPE html><html> <head> <meta charset" utf-8"> <meta name"author"…

Flask--讀取配置參數的方式

文章目錄方法1. 使用配置文件方法2. 使用對象配置參數方法3. 直接操作config的字典對象項目實例方法1. 使用配置文件 首先將配置參數寫在文件中&#xff0c;例如&#xff1a;config.cfg 然后導入: app Flask("__name__") app.config.from_pyfile("config.cf…

g開頭的C語言編程軟件,C語言函數大全(g開頭)

函數名: gcvt功 能: 把浮點數轉換成字符串用 法: char *gcvt(double value, int ndigit, char *buf);程序例:#include#includeint main(void){char str[25];double num;int sig 5; /* significant digits *//* a regular number */num 9.876;gcvt(num, sig, str);printf(&quo…

什么是總體設計

總體設計的基本目的就是回答“概括地說&#xff0c;系統應該如何實現”這個問題&#xff0c;因此&#xff0c;總體設計又稱為概要設計或初步設計。總體設計階段的另一項重要任務是設計軟件的結構&#xff0c;也就是要確定系統中每個程序是由哪些模塊組成的&#xff0c;以及這些…

程序員成熟的標志《程序員成長路線圖:從入門到優秀》

對好書進行整理&#xff0c;把好內容共享。 我見證過許多的程序員的成長&#xff0c;他們很多人在進入成熟期之后&#xff0c;技術上相對較高&#xff0c;一般項目開發起來比較自信&#xff0c;沒有什么太大的困難&#xff0c;有的職位上也有所提升&#xff0c;成了項目經理、…

Diango博客--1.Django的接客之道

文章目錄0.思路引導1.實現最簡單的HelloWorld2.實現最簡單的HelloWorld(使用Templates)0.思路引導 django 的開發流程&#xff1a; 即首先配置 URL&#xff0c;把 URL 和相應的視圖函數綁定&#xff0c;一般寫在 urls.py 文件里&#xff0c;然后在工程的 urls.py 文件引入。 …

c語言is int number,C語言中NSInteger,NSNumber以及Int的區別

NSInteger和NSNumber首先:NSInteger,NSNumber并沒有什么關系,更不要想當然的以為二者還有什么繼承關系,甚至還有人問NSInteger是不是NSNumber的子類?答案當然是NO!!!NSInteger只是一個基本的數據類型,而NSNumber是OC的對象,并且NSNumber繼承自NSValue,NSValue又繼承自NSObject…

Git的GUI工具sourcetree的使用

一、Git的學習這部分學習廖雪峰的git教程&#xff0c;參加以下鏈接&#xff1a;https://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b0001、首先是git的基本概念&#xff0c;如下圖所示&#xff1a;整個git管理主要分為工作區、版本庫&#xff0…

YY一下,扎克伯格做了一個什么樣的AI家居助手?

對于這款令小扎太太抓狂的AI家居助手&#xff0c;難道就沒人好奇嗎&#xff1f; 據說&#xff0c;扎克伯格每年都要給自己定個目標&#xff0c;而他也即將完成今年的目標——打造一個AI家居助手。 當初&#xff0c;在定下這個目標時&#xff0c;小扎為我們簡單描述了一下&…

Diango博客--2.博客從“裸奔”到“有皮膚”

文章目錄0.思路引導1.更改視圖函數&#xff0c;從數據庫中獲取數據2.網上下載模板&#xff0c;添加靜態文件3.修改模板Templates中css、js文件的加載路徑4.修改模板&#xff0c;引入模板變量&#xff0c;獲取數據庫數據0.思路引導 前文的Hello World 級別的視圖函數特別簡單&a…