def detail(): """订单详情""" g.title = u'订单详情' g.page_type = '' order_id = toint(request.args.get('order_id', '0')) is_diliver = toint(request.args.get('is_diliver', '0')) if order_id <= 0: return u'参数出错' order_info = Order.query.get_or_404(order_id) if not order_info: return u'找不到订单信息' user = User.query.get(order_info.uid) if not user: return u'找不到对应的用户' user_device = UserDevice.query.filter(UserDevice.uid == user.uid).first() order_goods_list = OrderGoods.query.filter( OrderGoods.order_id == order_id).all() for order_goods in order_goods_list: lottery = Lottery.query.get(order_goods.lottery_id) order_goods.lottery_name = lottery.lottery_name if lottery else '' address = OrderAddress.query.filter( OrderAddress.order_id == order_id).first() coupon_list = Coupon.query.filter( Coupon.order_id == order_info.order_id).all() shipping_list = Shipping.query.order_by(Shipping.shipping_id.desc()).all() data, status_text = KuaiDi100StaticMethodsService.search( order_info.shipping_code, order_info.shipping_sn) log_info('### data:%s, status_text:%s' % (data, status_text)) if order_info.order_type not in (0, 1, 2, 3): return u'找不到订单类型' if order_info.order_type == 2: g.title = u'充值订单详情' return render_template('order/recharge_detail.html.j2', order=order_info, **locals()) if order_info.order_type == 3: g.title = u'一元购订单详情' return render_template('order/lottery_detail.html.j2', order=order_info, **locals()) g.title = u'普通订单详情' return render_template('order/ordinary_detail.html.j2', order=order_info, **locals())
def child_menu_list(id=0): """子菜单列表""" if id <= 0: return u'参数出错' permission_list = db.session.query(Permission.permission_id, Permission.endpoint_name).\ filter(Permission.parent_id > 0).\ filter(Permission.parent_id == id).all() log_info(permission_list) return permission_list
def news_save(): """ 保存资讯 """ g.page_type = '' g.title = u'保存资讯' form = request.form news_id = toint(form.get('news_id', 0)) sns = SaveNewsService(form, news_id) if not sns.check(): g.errmsg = sns.errmsg log_info(u'### g.errmsg:%s' % g.errmsg) return render_template('news/news_info.html.j2', f=form) sns.save() return redirect(url_for('news.news_list'))
def st_save(): """保存规格模板""" args = request.args st_name = args.get('st_name', '').strip() st_id = toint(args.get('st_id', '0')) log_info('### st_name:%s, st_id:%s'%(st_name, st_id)) if st_id > 0: st = SpecTemplate.query.get(st_id) if not st: return u'获取模板失败' else: st = SpecTemplate.create(add_time=int(time.time())) st.update(st_name=st_name, commit=True) return u'ok'
def _get_message(self, os, title, content, data={}): """获取消息体 :param os 操作系统 ios|android :param title 标题 :param content 内容 :param data 自定义键值对,key和value都必须是字符串 :return msg """ custom = {} for k, v in data.items(): if isinstance(v, types.StringType) or isinstance( v, types.UnicodeType): custom[k] = v.encode('utf8') else: custom[k] = str(v) msg = None if os == 'android': msg = xinge.Message() msg.type = xinge.Message.TYPE_MESSAGE else: msg = xinge.MessageIOS() msg.type = xinge.Message.TYPE_NOTIFICATION msg.title = title.encode('utf8') msg.content = content.encode('utf8') # 消息为离线设备保存的时间,单位为秒。默认为0,表示只推在线设备 msg.expireTime = 300 # 自定义键值对,key和value都必须是字符串 msg.custom = data # 通知展示样式,仅对通知有效 # 样式编号为2,响铃,震动,不可从通知栏清除,不影响先前通知 style = xinge.Style(2, 1, 1, 1, 0) msg.style = style if os == 'ios': msg.alert = msg.content msg.badge = self.unread_num msg.sound = 'default' log_info('alert:%s, badge:%s, sound:%s' % (msg.alert, msg.badge, msg.sound)) return msg
def _get_xingeapp(self, os, client_flag): """获取信鸽推送app""" access_id_name = 'XINGE_%s_%s_ACCESS_ID' % (client_flag, os.upper()) secret_key_name = 'XINGE_%s_%s_SECRET_KEY' % (client_flag, os.upper()) access_id = current_app.config[access_id_name] secret_key = current_app.config[secret_key_name] if not access_id or not secret_key: log_info('[PushError] %s:%s, %s:%s' % (access_id_name, access_id, secret_key_name, secret_key)) return None log_info('access_id:%s, secret_key:%s' % (access_id, secret_key)) app = xinge.XingeApp(access_id.encode('utf8'), secret_key.encode('utf8')) log_debug('Push get app ok') return app
def st_add(): """添加商品模板""" args = request.args goods_id = toint(args.get('goods_id', '0')) st_id = toint(args.get('st_id', '0')) if st_id <= 0 or goods_id <= 0: return u'参数出错' st = SpecTemplate.query.get(st_id) s_list = Spec.query.filter(Spec.st_id == st.st_id).all() goods = Goods.query.get(goods_id) if not goods: return u'获取商品信息失败' gs = None for s in s_list: is_gs_exit = GoodsSpec.query.filter(GoodsSpec.goods_id == goods_id).\ filter(GoodsSpec.spec_key == s.spec_key).\ filter(GoodsSpec.spec_value == s.spec_value).first() if is_gs_exit: log_info('### is_gs_exit:%s'% is_gs_exit) continue gs = GoodsSpec.create(goods_id=goods_id, spec_key=s.spec_key, spec_value=s.spec_value, sort_order=s.sort_order, add_time=int(time.time())) if not gs: return u'新增模板已经存在' gs.update(commit=True) return u'ok'
def file_upload(): """文件上传""" form = request.form cat = form.get('cat', 'sys') one_file = request.files.get('file') file_type = toint(form.get('file_type', '1')) # 1.图片 2.视频 file_url = 'error' if one_file: if file_type == 2: # push_type 1.图片 2.视频 3.音频 4.文档 push_type = 2 oss = QiNiuOSS('video', push_type, current_app.config['SAVE_TARGET_PATH']) try: oss.save(one_file) file_url = oss.put_to_oss() except IOError, e: log_info(u'### 只允许是视频文件:%s' % e) pass except Exception, e: log_info(u'### 视频上传失败:%s' % e) pass
def database_clear(): import mysql.connector args = request.args if request.method == 'GET' else request.form table_name_str = args.get('table_name_str', 'user_check_code').strip() user = args.get('user', 'root') password = args.get('password', '') host = args.get('host', '127.0.0.1') database = args.get('database', 'didi_car') table_name_list = table_name_str.split(',') conn = mysql.connector.connect(user=user, password=password, host=host, database=database) cursor = conn.cursor() for table_name in table_name_list: cursor.execute('truncate table `%s`' % table_name) log_info(u'### %s表已经被清空' % table_name) # cursor.rowcount conn.commit() cursor.close() return u'ok'
def easy_query_filter(Object, q, query_dict={}): """查询""" if not Object: log_info(u'请传入查询对象。') return q if not q: log_info(u'请传入q。') return q query_name_list = query_dict.keys() for query_name in query_name_list: attr = query_dict.get(query_name) if isinstance(attr, int) == True: if attr >= 0: q = q.filter(getattr(Object, query_name) == attr) continue continue if attr: if query_name[-4:] == 'time': if query_name[:5] == 'begin': begin_time = time.mktime(time.strptime(attr, '%Y-%m-%d')) q = q.filter(getattr(Object, query_name[6:]) >= begin_time) continue if query_name[:3] == 'end': end_time = time.mktime(time.strptime( attr, '%Y-%m-%d')) + 24 * 3600 q = q.filter(getattr(Object, query_name[4:]) <= end_time) continue q = q.filter( getattr(Object, query_name).like(u'%' + attr + u'%')) continue q = q.filter(getattr(Object, query_name).like(u'%' + attr + u'%')) continue return q
def search(com, num, muti=1, order=u'desc'): """ 查询 """ customer = current_app.config.get('KUAIDI100_CUSTOMER', '') key = current_app.config.get('KUAIDI100_KEY', '') data = [] status_text = u'暂无物流信息' url = u'http://poll.kuaidi100.com/poll/query.do' param = u'{"com":"%s", "num":"%s"}' % (com, num) _sign = u'%s%s%s' % (param, key, customer) sign = hashlib.md5(_sign).hexdigest() sign = sign.upper() data = {'customer':customer, 'param':param, 'sign':sign} res = requests.post(url, data=data) res.encoding = 'utf8' log_info('[InfoKuaiDi100StaticMethodsServiceSearch][RequestInfo] url:%s res.text:%s' % (url, res.text)) status_code = toint(res.status_code) if status_code == 200: ret = res.json() status = ret.get('status', None) state = toint(ret.get('state', -1)) data = ret.get('data', []) if state == 0: status_text = u'在途中' elif state == 1: status_text = u'揽件中' elif state == 2: status_text = u'疑难' elif state == 3: status_text = u'已签收' elif state == 4: status_text = u'退签中' elif state == 5: status_text = u'派件中' elif state == 6: status_text = u'已退回' else: status_text = u'暂无物流信息' else: log_info('[InfoKuaiDi100StaticMethodsServiceSearch][SearchError] url:%s res.text:%s' % (url, res.text)) log_info('### =============>state:%s, status_text:%s, res.status_code:%s'%(state, status_text, status_code)) return (data, status_text)
def push_user(self, uid, title, content, data={}, client_flag='USER', sms=False): """用户端推送 :param title 标题 :param content 内容 :param data 自定义键值对,key和value都必须是字符串 """ user = db.session.query(User.pushtoken, User.uid, UserDevice.device_os,UserDevice.ud_id).\ filter(User.uid == UserDevice.uid).\ filter(User.uid == uid).first() if user is None: log_info('[PushUser] Can not push user. user is None.') return None if (user.os not in ('ios', 'android') or not user.pushtoken): log_info( '[PushUser] Can not push user. uid:%d, os:%s, pushtoken:%s' % (uid, user.os, user.pushtoken)) return None # 初始化app对象,设置有效的access id和secret key xingeapp = self._get_xingeapp(user.os.upper(), client_flag) if xingeapp is None: return None msg = self._get_message(user.os, title, content, data) # 第三个参数environment仅在iOS下有效。ENV_DEV表示推送APNS开发环境 tmp = xingeapp.PushSingleDevice(user.pushtoken.encode('utf8'), msg, xinge.XingeApp.ENV_PROD) log_info(tmp) return tmp
if not self.salon: self.errmsg['submit'] = u'群组不存在' # 检查 - 群组原图是否合法 if _salon_img: oss = AliyunOSS('user', current_app.config['SAVE_TARGET_PATH']) try: oss.save(_salon_img) self.salon_img = oss.put_to_oss() except UploadNotAllowed, e: self.errmsg['salon_img'] = u'只允许是图片文件' except Exception, e: self.errmsg['salon_img'] = u'原图上传失败' if len(self.errmsg) > 0: log_info(self.errmsg) return False return True def save(self): """ 保存 """ salon_name = self.form.get('salon_name', '').strip() desc = self.form.get('desc', '').strip() sort_order = toint(self.form.get('sort_order', 0)) us_id = toint(self.form.get('us_id', 0)) uid = session['uid'] if self.is_new: self.salon = UserSalon.create(add_time=self.current_time)
def save(self, form): """保存优惠券信息""" self._check_param(form) if self.errmsg: return self.errmsg cb_name = form.get('cb_name', '') coupon_name = form.get('coupon_name', '') coupon_amount = Decimal(form.get('coupon_amount', '0')) limit_amount = Decimal(form.get('limit_amount', '0')) publish_num = toint(form.get('publish_num', '0')) begin_time = form.get('begin_time', '') end_time = form.get('end_time', '') is_valid = toint(form.get('is_valid', '0')) goods_id_list = form.getlist('goods_id') goods_id_all = form.get('goods_id_all', '') coupon_from = form.get('coupon_from', '') valid_days = toint(form.get('valid_days', '0')) for k, v in form.items(): log_info('[SaveCouponBatch] %s:%s' % (k, v)) begin_time = int(time.mktime(time.strptime(begin_time, '%Y-%m-%d'))) end_time = int(time.mktime(time.strptime(end_time, '%Y-%m-%d'))) limit_goods = 'all' limit_goods_name = u'全场通用' # if goods_id_all != 'all': # goods_list = Goods.query.all() # if len(goods_id_list) != len(goods_list): # limit_goods = ','.join(goods_id_list) # limit_goods_name = u'' # goods_dict = {} # for goods in goods_list: # goods_dict[goods.goods_id] = goods.goods_name # limit_goods_name_list = [] # for goods_id in goods_id_list: # goods_id = toint(goods_id) # limit_goods_name_list.append(goods_dict.get(goods_id, '')) # limit_goods_name = ','.join(limit_goods_name_list) self.coupon_batch.cb_name = cb_name self.coupon_batch.coupon_name = coupon_name self.coupon_batch.coupon_amount = coupon_amount self.coupon_batch.limit_amount = limit_amount self.coupon_batch.publish_num = publish_num self.coupon_batch.begin_time = begin_time self.coupon_batch.end_time = end_time self.coupon_batch.is_valid = is_valid self.coupon_batch.limit_goods = limit_goods self.coupon_batch.limit_goods_name = limit_goods_name self.coupon_batch.coupon_from = coupon_from self.coupon_batch.valid_days = valid_days self.coupon_batch.update_time = int(time.time()) update_dict = { 'limit_amount': limit_amount, 'coupon_name': coupon_name, 'coupon_amount': coupon_amount, 'begin_time': begin_time, 'end_time': end_time, 'limit_goods': limit_goods, 'limit_goods_name': limit_goods_name, 'coupon_from': coupon_from } if is_valid == 0: update_dict['is_valid'] = 0 Coupon.query.filter( Coupon.cb_id == self.coupon_batch.cb_id).update(update_dict) db.session.commit() return {}
class ApiJsonService(object): """ API(josn)服务 """ def __init__(self, url, params=None, method='GET', timeout=10, cookie_jar=None, json_type='me', headers=[('language', 'en')]): self.url = url self.params = params self.method = method self.timeout = timeout self.cookie_jar = cookie_jar self.json_type = json_type self.headers = headers self.res = None self.json = {} self.ret = None self.msg = None self.data = None self.set_cookie = '' self.encoding = None def call_service(self): """ 调用远程服务 """ try: encode_data = None if self.params is not None: if self.method == 'GET': self.url += '?' + urlencode(self.params) log_debug(self.url) elif self.method == 'POST': encode_data = urlencode(self.params) opener = urllib2.build_opener() opener.addheaders = self.headers if self.cookie_jar is not None: opener = urllib2.build_opener( urllib2.HTTPCookieProcessor(self.cookie_jar)) res_obj = opener.open(self.url, data=encode_data, timeout=self.timeout) self.set_cookie = res_obj.info().getheader('Set-Cookie') self.res = res_obj.read() # encoding self.encoding = guess_json_utf(self.res) if self.encoding: self.res = self.res.decode(self.encoding) self.json = json.loads(self.res) self.ret = self.json.get('ret') self.msg = self.json.get('msg') self.data = self.json.get('data') except Exception, e: log_debug('[JSONService] url:%s, response:%s, expetion:%s' % (self.url, self.res, e)) return False if self.ret != 0 and self.json_type == 'me': log_info('[JSONService] url:%s, response:%s' % (self.url, self.res)) return False return True
def coupon_acquire(): """获取优惠券""" g.page_type = 'form' form = request.form mobile = form.get('mobile', '').strip() cb_id = toint(form.get('cb_id', '0')) coupon_id = toint(form.get('coupon_id', '0')) if cb_id <= 0: return u'参数出错' coupon_batch = CouponBatch.query.get(cb_id) if coupon_batch is None: return u'优惠券批次不存在' mobile = mobile.replace('\r', '') mobile_list = mobile.split('\n') index, mobile_count = 0, len(mobile_list) for m in mobile_list: if not ismobile(m): log_info('[GiveCoupon] mobile is not correct. mobile:%s' % m) user = User.query.filter(User.mobile == m).first() if user is None: log_info('[GiveCoupon] user not found. mobile:%s' % m) continue # once = User.query.filter(User.uid == Coupon.uid).\ # filter(User.mobile == m).\ # filter(Coupon.cb_id == cb_id).first() # if once is not None: # log_info('[GiveCoupon] user can only get coupon_banch for once. mobile:%s' % m) # continue index += 1 log_info('[GiveCoupon] %d/%d cb_id:%d, mobile:%s' % (index, mobile_count, cb_id, m)) coupon_batch.give_num += 1 coupon_batch.update_time = int(time.time()) begin_time, end_time = coupon_batch.begin_time, coupon_batch.end_time if coupon_batch.valid_days > 0: begin_time = get_today_unixtime() end_time = begin_time + coupon_batch.valid_days * 24 * 60 * 60 coupon = Coupon() coupon.is_valid = 1 coupon.add_time = int(time.time()) coupon.uid = user.uid coupon.begin_time = begin_time coupon.end_time = end_time coupon.cb_id = coupon_batch.cb_id coupon.coupon_name = coupon_batch.coupon_name coupon.coupon_amount = coupon_batch.coupon_amount coupon.limit_amount = coupon_batch.limit_amount coupon.limit_goods = coupon_batch.limit_goods coupon.limit_goods_name = coupon_batch.limit_goods_name coupon.coupon_from = coupon_batch.coupon_from db.session.add(coupon) if index % 50 == 0: db.session.commit() # 发送推送 xps = XingePushService() xps.push_user(user.uid, u'101计划', u'系统赠送您一张' + coupon_batch.coupon_name, { 'trans_id': 0, 'trans_type': 'me' }, client_flag='USER') if index % 50 != 0: db.session.commit() return redirect(url_for('coupon.user_coupon'))