- Flask是一款MVC框架,主要是从模型、视图、模板三个方面对Flask框架有一个全面的认识,
- 通过完成作者-读书功能,先来熟悉Flask框架的完整使用步骤。
- 操作步骤为:
- 1.创建项目
- 2.配置数据库
- 3.定义模型类
- 4.定义视图并配置URL
- 5.定义模板
- 前面说了创建项目的流程,今天主要从配置到用户,主要根据思维导图来说,先看思维导图
-
主要有以下几个方面:
1.房屋
- 新建house_views.py,创建蓝图并注册
- 需要完成的功能如下:
- myhouse.html:我的房源
- newhouse.html:发布新房源
- index.html:首页
- search.html:搜索结果页
- detail.html:房屋详细页
2.订单
- 新建booking_views.py,创建蓝图并注册
- 订单模块主要包括的功能如下
- booking.html:预订页面
- orders.html:我的订单,作为房客的订单
- lorders.html:客户订单,作为房东的订单
主要根据思维导图,代码加注释的方法来说明:
1.房屋
完整代码:https://gitee.com/itpython/ihome/tree/bj14/ihome
- 新建house_views.py
#coding=utf-8
from flask import Blueprint, jsonify
from flask import request
from flask import sessionfrom qiniu_sdk import put_qiniu
from status_code import REThouse_blueprint=Blueprint('house',__name__)from flask import current_app
from flask import jsonfrom models import Area, Facility, HouseImage, House, User, Order#获取地区信息,并进行缓存
def get_areas():area_dict_list=current_app.redis.get('area_list')if not area_dict_list:area_list=Area.query.all()arear_dict_list=[area.to_dict() for area in area_list]current_app.redis.set('area_list',json.dumps(area_dict_list))else:#存储到redis后会被转换成字符串,所以取出来后需要转换area_dict_list=json.loads(area_dict_list)return area_dict_list#获取设施信息并缓存
def get_facilities():facility_dict_list=current_app.redis.get('facility_list')if not facility_dict_list:facility_list=Facility.query.all()facility_dict_list=[facility.to_dict() for facility in facility_list]current_app.redis.set('facility_list',json.dumps(facility_dict_list))else:facility_dict_list=json.loads(facility_dict_list)return facility_dict_list@house_blueprint.route('/area_facility',methods=['GET'])
def newhouse():#查询地址kkkkarea_dict_list=get_areas()#查询设施facility_dict_list=get_facilities()#构造结果并返回return jsonify(area=area_dict_list,faciclity=facility_dict_list)#保存房屋图片
@house_blueprint.route('/newhouse_image')
def newhouse_image():#接受房屋编号house_id=request.form.get('house_id')#接受图片信息f1=request.files.get('house_image')#保存到七牛云上url=put_qiniu(f1)#保存图片对象image=HouseImage()image.house_id=house_idimage.url=urlimage.add_update()#房屋的默认图片house=House.query.get(house_id)if not house.index_image_url:house.index_image_url=urlhouse.add_update()#返回图片信息return jsonify(code=RET.OK,url=current_app.config.get("QINIU_URL")+url)#保存信息
@house_blueprint.route('/',methods=['POST'])
def newhouse_save():#接收数据params=request.form.to_dict()facility_ids=request.form.getlist('facility')#创建对象并保存house = House()house.user_id = session['user_id']house.area_id = params.get('area_id')house.title = params.get('title')house.price = params.get('price')house.address = params.get('address')house.room_count = params.get('room_count')house.acreage = params.get('acreage')house.beds = params.get('beds')house.unit = params.get('unit')house.capacity = params.get('capacity')house.deposit = params.get('deposit')house.min_days = params.get('min_days')house.max_days = params.get('max_days')#根据设施的编号查询设施对象if facility_ids:facility_list=Facility.query.filter(Facility.id.iin_(facility_ids)).all()house.facilities=facility_listhouse.add_update()#返回结果return jsonify(code=RET.OK,house_id=house.id)#我的房屋
@house_blueprint.route('/',methods=['GET'])
def myhouse():user_id=session['user_id']user=User.query.get(user_id)if user.id_name:#已经完成实名认证,查询当前用户的房屋信息house_list=House.query.filter(House.user_id==user_id).order_by(House.id.desc())house_list2=[]for house in house_list:house_list2.append(house.to_dict())return jsonify(code=RET.OK,hlist=house_list2)else:#没有完成实名认证return jsonify(code=RET.USERERR)#查询房屋与设施,如果是自己的则查询不出来,目的就是不让自己预定自己的房子
@house_blueprint.route('/<init:id>',methods=['GET'])
def house_detail(id):#查询房屋信息house=House.query.get(id)#查询设施信息facility_list=get_facilities()#判断当前房屋是不是自己booking=1if 'user_id' in session:if house.user_id==session['user_id']:booking=0return jsonify(house=house.to_full_dict(),facility_list=facility_list,booking=booking)#搜索房屋
@house_blueprint.route('/search',methods=['GET'])
def search():#接收参数dict=request.argsarea_id=int(dict.get('aid'))begin_date=dict.get('sd')end_date=dict.get('ed')sort_key=dict.get('sk')#满足地区条件hlist=House.query.filter(House.area_id==area_id)#不能查询自己发布的房源,排除当前用户发布的房屋if 'user_id' in session:hlist=hlist.filter(House.user_id!=(session['user_id']))#满足事件条件,当订单完成后再完成时间限制order_list=Order.query.filter(Order.status!='REJECTED')#情况一:# order_list1=Order.query.filter(Order.begin_date>=begin_date,Order.end_date<=end_date)#情况二order_list2=Order.query.filter(Order.begin_date<begin_date,Order.end_date>end_date)#情况三order_list3=Order.query.filter(Order.end_date>=begin_date,Order.end_date<=end_date)#情况四:order_list4=Order.query.filter(Order.begin_date>=begin_date,Order.begin_date<=end_date)#获取订单中的房屋编号house_ids=[order.house_id for order in order_list2]for order in order_list3:house_ids.append(order.house_id)for order in order_list4:if order.house_id not in house_ids:house_ids.append(order.house_id)hlist=hlist.filter(House.id.notin_(house_ids))#排序规则,默认根据最新排列sort=House.id.desc()if sort_key=='booking':sort=House.order_count.desc()elif sort_key=='price-inc':sort=House.price.asc()elif sort_key=='price-des':sort=House.price.desc()hlist=hlist.order_by(sort)hlist2=[]for house in hlist:hlist2.append(house.to_dict())#获取地区信息if request.args.get('area','0')=='1':alist=get_areas()else:alist=[]return jsonify(hlist=hlist2,alist=alist)
订单
- 新建booking_views.py
# coding=utf-8
from flask import Blueprint,jsonify,request,session
order_blueprint=Blueprint('order',__name__)
from datetime import datetime
from models import House,Order
from status_code import RET,ret_map
from my_decorators import is_login
import logging#查询指定编号的房屋信息
@order_blueprint.route('/house/<int:id>')
def booking_house(id):house=House.query.get(id)return jsonify(house=house.to_dict())#创建订单
@is_login
@order_blueprint.route('/',methods=['POST'])
def booking():#接收参数dict=request.formhouse_id=int(dict.get('house_id'))start_date=datetime.strptime(dict.get('start_date'),'%Y-%m-%d')end_date=datetime.strptime(dict.get('end_date'),'%Y-%m-%d')#验证有效性if not all([house_id,start_date,end_date]):return jsonify(code=RET.PARAMERR,msg=ret_map[RET.PARAMERR])if start_date>end_date:return jsonify(code=RET.PARAMERR,msg=ret_map[RET.PARAMERR])#查询房屋对象try:house=House.query.get(house_id)except:logging.error(u'下订单-查询房屋出错,房屋编号%d'%house_id)return jsonify(code=RET.DBERR,msg=ret_map[RET.DBERR])#创建订单对象order=Order()order.user_id=session['user_id']order.house_id=house_idorder.begin_date=start_dateorder.end_date=end_dateorder.days=(end_date-start_date).days+1order.house_price=house.priceorder.amount=order.days*order.house_pricetry:order.add_update()except:logging.error(u'下订单-出错')return jsonify(code=RET.DBERR,msg=ret_map[RET.DBERR])#返回信息return jsonify(code=RET.OK)#作为租客查询订单
@is_login#
@order_blueprint.route('/',methods=['GET'])
def orders():uid=session['user_id']order_list=Order.query.filter(Order.user_id==uid).order_by(Order.id.desc())order_list2=[order.to_dict() for order in order_list]return jsonify(olist=order_list2)#作为房东查询订单
@is_login
@order_blueprint.route('/fd',methods=['GET'])
def lorders():uid=session['user_id']#查询当前用户的所有房屋编号hlist=House.query.filter(House.user_id==uid)hid_list=[house.id for house in hlist]#根据房屋编号查找订单order_list=Order.query.filter(Order.house_id.in_(hid_list)).order_by(Order.id.desc())#构造结果olist=[order.to_dict() for order in order_list]return jsonify(olist=olist)#修改状态
@order_blueprint.route('/<int:id>',methods=['PUT'])
def status(id):#接收参数:状态status=request.form.get('status')#查找订单对象order=Order.query.get(id)#修改order.status=status#保存order.add_update()return jsonify(code=RET.OK)