示例#1
0
def get_qq_account_info(user_profile, social_account, can_use_local=True):
	qq_account_info = None

	if can_use_local:
		try:
			qq_account_info = _get_local_qq_account_info(social_account)
		except:
			notify_message = u"从本地获取QQ账号基本信息失败,openid:{}, cause:\n{}".format(
				social_account.openid, unicode_full_stack())
			watchdog_error(notify_message)

	if qq_account_info and qq_account_info.head_img and qq_account_info.nickname:
		return qq_account_info

	#需要进行方式微博api进行实时获取
	qq_account_info_via_api = _get_qq_account_info_via_api(user_profile, social_account)
	if qq_account_info and qq_account_info_via_api:
		try:
			_update_local_qq_account_info(social_account, qq_account_info_via_api)
		except:
			notify_message = u"更新本地QQ账号基本信息失败,openid:{}, cause:\n{}".format(
				social_account.openid, unicode_full_stack())
			watchdog_fatal(notify_message)

	elif qq_account_info_via_api:
		try:
			_save_local_qq_account_info(social_account, qq_account_info_via_api)
		except:
			notify_message = u"添加本地QQ账号基本信息失败,openid:{}, cause:\n{}".format(
				social_account.openid, unicode_full_stack())
			watchdog_fatal(notify_message)

	return qq_account_info_via_api
示例#2
0
	def _poll_response(self):
		"""
		发送快递100 订阅请求,返回成功与否信息
		"""
		# post中的param的json

		param_json_data = {'Code': self.express_company_name_kdniao,'Item': [
                           {'No': str(self.express_number),'Bk': str(self.express.id)},
                           ]}
		DataSign= self._encrypt(str(param_json_data))
		params = {
		"RequestData": param_json_data,
		"EBusinessID": self.Business_id ,
		"RequestType": "1005",
		"DataSign": DataSign,
		"DataType": "2"
		}

		#将数据处理为RequestData=xxx&DataType=xxx这种格式的
		param_str = urllib.urlencode(params)
		
		verified_result = ''
		try:
			verified_result = post(KdniaoExpressConfig.req_url, param_str)
			watchdog_info(u"发送快递鸟 订阅请求 url: {},/n param_data: {}, /n response: {}".format(
				KdniaoExpressConfig.req_url, 
				param_str,
				verified_result.decode('utf-8')), type=self.express_config.watchdog_type)
		except:
			watchdog_error(u'发送快递鸟 订阅请求 失败,url:{},data:{},原因:{}'.format(KdniaoExpressConfig.req_url,
				param_str,
				unicode_full_stack()), type=self.express_config.watchdog_type)

		return verified_result
示例#3
0
	def get_express_poll(self):
		# 如果是空不处理
		if self.express_company_name_kdniao is '' or self.express_number is '':
			return False

		# 是否已经订阅过该订单,并且成功
		status = self._is_poll_by_order()
		if status:
			return True

		# 保存快递信息	
		self.express = self._save_poll_order_id()

		# 发送订阅请求
		data = self._poll_response()
		data = json.loads(data)
		result = True if data.get('Success') == "true" or data.get('Success') is True else False

		if result:
			# 修改快递信息状态,self.express.status = 200订阅成功,0未订阅
			self.express.status = 200
			self.express.send_count = self.express.send_count + 1
			self.express.abort_receive_message = ""
			self.express.save()
			return True
		else:
			if data and data.get('Reason'):
				print "Reason:",data.get('Reason')
				self.express.status = 0
				self.express.abort_receive_message = data.get('Reason')
				self.express.save()
				watchdog_error(u'发送快递鸟 订阅请求存在问题,url:{},订单id:{},原因:{}'.format(KdniaoExpressConfig.req_url,
					self.order_id,
					data.get('Reason')), type=self.express_config.watchdog_type)
			return False
示例#4
0
	def _is_poll_by_order(self):
		try:
			pushs = ExpressHasOrderPushStatus.objects.filter(
					# order_id = self.order_id,
					express_company_name = self.order.express_company_name,
					express_number = self.order.express_number
					)
			if pushs.count() > 0:
				push = pushs[0]

				# 不需要重新发送订阅请求的状态
				if push.status in EXPRESS_NOT_PULL_STATUSES:
					return True

				# 超过4次发送就不再发送次快递
				if push.send_count >= 4:
					return True
					
				# 关闭,重发订阅,由于某种原因订阅失败
				if push.abort_receive_message and len(push.abort_receive_message) > 0:
					return False

				# 第一次发送订阅
				if push.status == EXPRESS_PULL_SUCCESS_STATUS and push.send_count > 0:
					return True

			return False
		except:
			watchdog_error(u'快递鸟tool_express_has_order_push_status表异常,获取订单信息,express_company_name:{},express_number:{}'.format(self.order.express_company_name, self.order.express_number), self.express_config.watchdog_type)
			return False
示例#5
0
def update_weizoom_mall_sync_product_status(request, product, update_data):
    try:
        relations = models.WeizoomHasMallProductRelation.objects.filter(mall_product_id=product.id, is_deleted=False)
        if relations.count() > 0:
            weizoom_store_user_ids = []
            weizoom_product_ids = []
            weizoom_product_id2user_id = dict()
            for relation in relations:
                weizoom_store_user_ids.append(relation.owner_id)
                weizoom_product_ids.append(relation.weizoom_product_id)
                weizoom_product_id2user_id[relation.weizoom_product_id] = relation.owner_id

            use_id2store_name = dict([(profile.user_id, profile.store_name)for profile in UserProfile.objects.filter(user_id__in=weizoom_store_user_ids)])
            products = models.Product.objects.filter(id__in=weizoom_product_ids)
            text = u'商品更新提示:\n'
            text += u'商品位置:\n'
            for product in products:
                text += (use_id2store_name[weizoom_product_id2user_id[product.id]] if use_id2store_name[weizoom_product_id2user_id[product.id]] else '') + '-' + (u'在售' if product.shelve_type else u'待售') + '-' + product.name + '\n'
            text += u'供货商:%s\n' % request.user_profile.store_name
            text += u'更新内容:%s\n' % u','.join(update_data)
            text += u'请及时处理!'
            relations.update(is_updated=True)
            if settings.MODE in ['develop', 'test'] or request.user.username == 'ceshi01':
                ding_util.send_to_ding(text, TEST_DING_GROUP_ID)
            else:
                ding_util.send_to_ding(text, DING_GROUP_ID)
    except:
        error_msg = u"update_weizoom_mall_sync_product_status error, cause:\n{}".format(unicode_full_stack())
        watchdog_error(error_msg)
示例#6
0
    def update_shared_url_pv(self, url, followed_member, member):

        try:
            url = remove_querystr_filed_from_request_url(url, 'from')
            url = remove_querystr_filed_from_request_url(url, 'isappinstalled')
            url = remove_querystr_filed_from_request_url(url, 'code')
            url = remove_querystr_filed_from_request_url(url, 'state')
            url = remove_querystr_filed_from_request_url(url, 'appid')
            url = remove_querystr_filed_from_request_url(url, 'workspace_id')
            url = remove_querystr_filed_from_request_url(url, 'workspace_id')
            #url_digest = hashlib.md5(url).hexdigest()
            shared_url_digest = hashlib.md5(url).hexdigest()
            shared_infos = MemberSharedUrlInfo.objects.filter(
                member=followed_member, shared_url=url)

            if shared_infos.count() > 0:
                self._increase_shared_url_pv(followed_member,
                                             shared_url_digest)
            else:
                title = MemberBrowseRecord.get_title(followed_member, url)
                MemberSharedUrlInfo.objects.create(
                    member=followed_member,
                    shared_url=url,
                    pv=1,
                    shared_url_digest=shared_url_digest,
                    title=title)
                Member.update_factor(followed_member)
        except:
            notify_message = u"更新分享链接的pv失败, url:{}, cause:\n{}".format(
                url, unicode_full_stack())
            watchdog_error(notify_message)
示例#7
0
文件: views.py 项目: chengdg/weizoom
def save_base64_img_file_local_for_webapp(request, ajax_file):
	date = time.strftime('%Y%m%d')
	dir_path_suffix = 'webapp/%d_%s' % (request.user_profile.user_id, date)
	dir_path = os.path.join(settings.UPLOAD_DIR, dir_path_suffix)

	if not os.path.exists(dir_path):
		os.makedirs(dir_path)

	#获取文件的扩展名
	file_name = '%s.%s' % (datetime.now().strftime("%Y_%m_%d_%H_%M_%S_%f"), 'png')
	ajax_path = '%s/%s' % (dir_path, file_name)
	ajax_file = ajax_file.split(',')

	image_content = base64.b64decode(ajax_file[1])
	image_file = open(ajax_path, 'wb')
	image_file.write(image_content)
	image_file.close()

	if __validate_image(ajax_path):
		try:
			image_path = upload_image_to_upyun(ajax_path,'/upload/%s/%s' % (dir_path_suffix, file_name))
			return image_path
		except:
			notify_msg = u"上传图片到又拍云时失败, cause:\n{}".format(unicode_full_stack())
			watchdog_error(notify_msg)
			return '/static/upload/%s/%s' % (dir_path_suffix, file_name)
		#return '/static/upload/%s/%s' % (dir_path_suffix, file_name)
	else:
		return None
示例#8
0
	def _verify_response(self):
		"""用登陆返回的code,获取access_token,发送请求"""
		param_data = {'client_id': self.weibo_config.app_id,
		        'client_secret': self.weibo_config.app_secret,
		        'grant_type': 'authorization_code',
				'redirect_uri': self.redirect_uri,
		        'code': self.code}
		verified_result = ''
		try:
			data = urllib.urlencode(param_data)
			request = urllib2.Request(self.WEIBO_AUTHORIZE_URL_TMPL,data)
			response = urllib2.urlopen(request)
			file = response.read()
			verified_result = file
			watchdog_info(u"get_access_token_data url: %s ,"
			                          u"param_data: %s" % (self.WEIBO_AUTHORIZE_URL_TMPL, data))
		except:
			watchdog_error(u'从Weibo获取access token失败,url:{},data:{},原因:{}'.format(self.WEIBO_AUTHORIZE_URL_TMPL,
				param_data,
				unicode_full_stack()))
			notify_message = u'从Weibo获取access token失败,url:{},data:{},原因:{}'.format(self.WEIBO_AUTHORIZE_URL_TMPL,
				param_data,
				unicode_full_stack())
			watchdog_fatal(notify_message)

		return verified_result
示例#9
0
def get_courses(request):
	count = request.GET.get('count', 10)
	page = request.GET.get('page', 1)
	webapp_owner_id = request.GET.get('webapp_owner_id', 1)
	try:
		courses, has_next = crm_api_views.list_course(page, 10000, 60)
	except:
		watchdog_error(u'crm_api_views.list_course 错误!!{}'.format(unicode_full_stack()))
		response = create_response(500)
		response.errMsg = u'获取数据失败'
		return response.get_response()
	
	shengjing_courses = ShengjingCourseRelation.objects.filter(owner_id=webapp_owner_id)
	shengjing_course_id2course = dict([(c.course_id, c) for c in shengjing_courses])
	shengjing_course_id2config = dict([(course.course_id, course.config)for course in shengjing_courses])
	cur_courses = []
	for c in courses:
		if c['id'] in shengjing_course_id2course:
			c['cover_pic_url'] = shengjing_course_id2config[c['id']].course_cover_pic_url
			c['introduction'] = shengjing_course_id2config[c['id']].introduction
			cur_courses.append(c)
	response = create_response(200)
	response.data.items = cur_courses
	response.data.pageinfo.has_next = has_next
	
	return response.get_response()
示例#10
0
文件: tasks.py 项目: chengdg/weizoom
def record_member_pv(self, member_id, url, page_title=''):
    try:
        """
		记录会员访问轨迹
		"""
        member = Member.objects.get(id=member_id)
        if member and url.find('api') == -1:
            MemberBrowseRecord.objects.create(title=page_title,
                                              url=url,
                                              member=member)

        #访问商品详情单独写到一张表里,方便统计商品的访问记录  duhao  20161221
        if 'module=mall' in url and 'model=product' in url and 'rid=' in url:
            result = urlparse.urlparse(url)
            params = urlparse.parse_qs(result.query, True)
            owner_id = params['woid'][0]
            product_id = params['rid'][0]
            referer = ''
            MemberBrowseProductRecord.objects.create(title=page_title,
                                                     url=url,
                                                     member=member,
                                                     owner_id=owner_id,
                                                     product_id=product_id,
                                                     referer=referer)
    except:
        notify_message = u"record_member_pv,member_id:{} cause:\n{}".format(
            member_id, unicode_full_stack())
        watchdog_error(notify_message)
        raise self.retry()
示例#11
0
def create_authorized_user_from_other_site(request):
    username = request.GET.get('un', None)
    password = request.GET.get('pw', None)
    logout_redirect_to = request.GET.get('logout_redirect_to', None)

    if (username is None) or (password is None):
        response = create_response(400)
    else:
        user = auth.authenticate(username=username, password=password)

        if user is not None:
            try:
                UserProfile.objects.filter(user=user).update(
                    logout_redirect_to=logout_redirect_to)
            except:
                error_msg = u"更新user('{}')的logout_redirect_to('{}')失败, cause:\n{}"\
                 .format(username, logout_redirect_to, unicode_full_stack())
                watchdog_error(error_msg, user_id=user.id)

            response = create_response(200)
            response.token = get_token_for_logined_user(user)
        else:
            response = create_response(400)

    return response.get_jsonp_response(request)
示例#12
0
def increase_father_member_integral_by_child_member_buyed(order, webapp_id):
    webapp_user_id = order.webapp_user_id
    integral_settings = IntegralStrategySttings.objects.filter(
        webapp_id=webapp_id)
    member = WebAppUser.get_member_by_webapp_user_id(webapp_user_id)
    if integral_settings.count() > 0 and member:
        father_member = MemberFollowRelation.get_father_member(member.id)
        if father_member and integral_settings[
                0].buy_via_offline_increase_count_for_author != 0:
            increase_member_integral(
                father_member,
                integral_settings[0].buy_via_offline_increase_count_for_author,
                BUY_INCREST_COUNT_FOR_FATHER)
            if order.final_price > 0 and integral_settings[
                    0].buy_via_offline_increase_count_percentage_for_author:
                try:
                    buy_via_offline_increase_count_percentage_for_author = float(
                        integral_settings[0].
                        buy_via_offline_increase_count_percentage_for_author)
                    integral_count = int(
                        order.final_price *
                        buy_via_offline_increase_count_percentage_for_author)
                    increase_member_integral(father_member, integral_count,
                                             BUY_INCREST_COUNT_FOR_FATHER)
                except:
                    notify_message = u"increase_father_member_integral_by_child_member_buyed cause:\n{}".format(
                        unicode_full_stack())
                    watchdog_error(notify_message)
示例#13
0
def update_member_source(request, args):
    """
	更新用户来源(?)
	"""
    member = member_info_util.get_request_member(request)
    if member is None:
        return None

    if member.source == -1:
        followed_member_token = member_info_util.get_followed_member_token(
            request)
        if followed_member_token:
            followed_member = member_info_util.get_member_by_member_token(
                followed_member_token)
            if followed_member and member and member.id != followed_member.id and followed_member.webapp_id == request.app.appid:
                member_models.Member.objects.filter(id=member.id).update(
                    source=member_models.SOURCE_BY_URL)
                try:
                    shared_url_digest = request.COOKIES.get(
                        member_settings.FOLLOWED_MEMBER_SHARED_URL_SESSION_KEY,
                        None)
                    if shared_url_digest:
                        integral.increase_shared_url_followers(
                            followed_member, shared_url_digest)
                except:
                    notify_message = u"MemberSouceMiddleware error, cause:\n{}".format(
                        unicode_full_stack())
                    watchdog_error(notify_message)
            else:
                member_models.Member.objects.filter(id=member.id).update(
                    source=member_models.SOURCE_SELF_SUB)
        else:
            member_models.Member.objects.filter(id=member.id).update(
                source=member_models.SOURCE_SELF_SUB)
示例#14
0
文件: tasks.py 项目: chengdg/weizoom
def __download_voice(message, weixin_mp_user_access_token):

    request_url = DownloadfileUrlTmpl.format(
        weixin_mp_user_access_token.access_token, message.media_id)
    #try:
    message.audio_url = request_url
    opener = __build_weixin_request_operner()
    audio_content = None
    for retryTimes in xrange(MaxRetryTimes):
        try:
            response = opener.open(request_url)
            audio_content = response.read()
            break
        except:
            #下载失败预警后重试三次
            watchdog_error(u"__download_voice, cause:\n{}".format(
                unicode_full_stack()))
    if audio_content.find('errmsg') >= 0 or len(audio_content) == 0:
        watchdog_error(
            u"__download_voice, cause:\n{}, {}".format(unicode_full_stack()),
            audio_content)
    else:
        #3. 转换音频格式(amr->mp3)
        mp3_url = _convert_amr_to_mp3(audio_content, message)
        if mp3_url:
            mp3_dir_url = mp3_url
            if mp3_url.find('/weapp/web/weapp') > -1:
                mp3_url = mp3_url.replace('/weapp/web/weapp/', '/')
            message.audio_url = mp3_url
            message.is_updated = True
            message.save()

            _upload_mp3_to_upyun(message.id, mp3_dir_url)
示例#15
0
def get_social_account_by_member_id(member_id):
	try:
		return MemberHasSocialAccount.objects.filter(member_id=member_id)[0].account
	except:
		error_msg = u"get_social_account:\n{}, {}".format(member_id, unicode_full_stack())
		watchdog_error(error_msg)
		return None
示例#16
0
            def pic_re(matched):
                pic_astr = matched.group("img_url")
                if pic_astr.startswith('/') and pic_astr.find('http') == -1:
                    pic_astr = pic_astr[1:]
                    pic_url = os.path.join(settings.PROJECT_HOME, '../',
                                           pic_astr)
                else:
                    pic_url = pic_astr

                pic_result = weixin_api.upload_content_media_image(
                    pic_url, True)
                pic_result_url = ''
                if pic_result.has_key('url'):
                    pic_result_url = pic_result['url']

                try:
                    if not pic_result_url:
                        watchdog_error(
                            u'上传多媒体文件失败 url:{}, pic_result:{}, weixin_resp:{}'.
                            format(pic_url, pic_result_url, pic_result))
                except:
                    pass
                pic_pre = matched.group("img_pre")
                pic_result_url = pic_pre + pic_result_url
                return pic_result_url
示例#17
0
	def inner_func():
		authed_appid = ComponentAuthedAppid.objects.filter(component_info=component, authorizer_appid=appid, is_active=True)[0]
		user_profile = UserProfile.objects.get(user_id= authed_appid.user_id)
		mpuser = WeixinMpUser.objects.get(owner_id=authed_appid.user_id)
		
		default_tag = member_models.MemberTag.get_default_tag(user_profile.webapp_id)
		default_grade = member_models.MemberGrade.get_default_grade(user_profile.webapp_id)
		try:
			integral_strategy_settings = member_models.IntegralStrategySttings.objects.get(webapp_id=user_profile.webapp_id)
		except:
			error_msg = u"获得user('{}')对应的IntegralStrategySttings构建cache失败, cause:\n{}"\
				.format(user_profile.user_id, unicode_full_stack())
			watchdog_error(error_msg, user_id=user_profile.user_id, noraise=True)
			integral_strategy_settings = None

		return {
			'value': {
				'user_profile': user_profile.to_dict(),
				'component_authed_appid': authed_appid.to_dict(),
				'mpuser': mpuser.to_dict(),
				'default_tag': default_tag.to_dict(),
				'default_grade': default_grade.to_dict(),
				'integral_strategy_settings': integral_strategy_settings.to_dict() if integral_strategy_settings else None
			}
		}
示例#18
0
def login_callback_handler(request):
    code = request.GET.get('code', None)
    state = request.GET.get('state', None)
    new_url = '/'
    response = HttpResponseRedirect(new_url)
    watchdog_info(u'从QQ登陆回调函数,code={},state={}'.format(code, state))
    if code:
        try:
            # 获取webapp_id 和 登陆后跳转地址
            webapp_id, new_url = get_shop_name_and_last_url(state)
            request = set_user_profile(request, webapp_id)
            # 获取 access_token
            qq_get_token = QQAccessToken(request, code)
            data = qq_get_token.get_access_token_data()
            token = data.get('access_token')

            # 获取 openId
            qq_get_open_id = QQOpenID(request, token)
            data = qq_get_open_id.get_open_id_data()
            openid = data.get('openid')

            # 创建 social_account
            social_account = save_social_account(openid, token,
                                                 SOCIAL_PLATFORM_QQ, webapp_id)
            response = HttpResponseRedirect(new_url)
            save_session(response, social_account)
        except:
            watchdog_error(u'从QQ登陆回调函数错误,error={}'.format(
                unicode_full_stack()))
    else:
        response = HttpResponseRedirect(new_url)
        notify_message = u'从QQ登陆回调函数错误,没有code{}'.format(request)
        watchdog_fatal(notify_message)

    return response
示例#19
0
    def api_get(request):
        """
		响应GET
		"""
        try:
            cur_color = random.choice(COLOR_LIST)
            captcha_image = captcha(
                drawings=[
                    background('#FFFFFF'),
                    text(fonts=['ARLRDBD.TTF'],
                         font_sizes=[30],
                         drawings=[offset(dx_factor=0.1, dy_factor=0.1)],
                         color=cur_color,
                         squeeze_factor=1.2),
                    curve(cur_color),
                    noise(),
                    # smooth()
                ],
                width=120,
                height=45)
            code_dict = init_check_code()
            rand_list = code_dict['clist']
            rand_str = code_dict['cstr']
            image = captcha_image(rand_list)
            # 将验证码转换成小写,并保存到session中
            request.session['checkcode'] = rand_str.lower()
            buf = StringIO.StringIO()
            image.save(buf, 'png')
            return HttpResponse(buf.getvalue(), 'image/png')
        except:
            error_msg = u"生成扫码抽奖验证码失败, cause:\n{}".format(unicode_full_stack())
            watchdog_error(error_msg)
            return HttpResponse('')
示例#20
0
文件: views.py 项目: chengdg/weizoom
def save_audio_file_for_mobileApp(request, ajax_file):
	date = time.strftime('%Y%m%d')
	dir_path_suffix = 'webapp/%d_%s' % (request.user_profile.user_id, date)
	dir_path = os.path.join(settings.UPLOAD_DIR, dir_path_suffix)
	if not os.path.exists(dir_path):
		os.makedirs(dir_path)
	#获取文件的扩展名
	amr_file_name = '%s.%s' % (time.strftime("%Y_%m_%d_%H_%M_%S"), 'amr')
	mp3_file_name = '%s.%s' % (time.strftime("%Y_%m_%d_%H_%M_%S"), 'mp3')
	amr_ajax_path = '%s/%s' % (dir_path, amr_file_name)
	mp3_ajax_path = '%s/%s' % (dir_path, mp3_file_name)
	# 保存amr文件
	file = open(amr_ajax_path, 'wb')
	file.write(ajax_file.read())
	file.close()
	# 转换格式为mp3
	_convert_amr_to_mp3(mp3_ajax_path,amr_ajax_path)
	time.sleep(1)
	if not os.path.exists(mp3_ajax_path):
		return False
	# 存到云
	try:
		audio_path = upload_image_to_upyun(mp3_ajax_path,'/upload/%s/%s' % (dir_path_suffix, mp3_file_name))
		return audio_path
	except:
		notify_msg = u"上传图片到又拍云时失败, cause:\n{}".format(unicode_full_stack())
		watchdog_error(notify_msg)
		print 'se'
		return '/static/upload/%s/%s' % (dir_path_suffix, mp3_file_name)
示例#21
0
    def _handle_keyword(self, context, from_weixin_user, is_from_simulator):
        # request = context.request
        message = context.message
        user_profile = context.user_profile

        response = None

        #获取匹配用户输入的自动答复规则
        if hasattr(message, 'content') is False:
            message.content = ''
        #response_rule = qa_util.find_answer_for(user_profile.webapp_id, message.content.lower())
        #从缓存中获取数据  duhao  2015-03-09
        response_rule = cache_util.find_answer_from_cache_for(
            user_profile.webapp_id, message.content.lower())
        if (response_rule is None) or (not response_rule.is_active):
            response_rule, response = self._build_response_without_auto_response_rule(
                user_profile, message, is_from_simulator)
        else:
            response = self._build_response_with_auto_response_rule(
                user_profile, message, response_rule, is_from_simulator)

        try:
            self._process_recorde_message(context, response_rule,
                                          from_weixin_user, is_from_simulator)
        except:
            notify_message = u"_process_recorde_message, cause:\n{}".format(
                unicode_full_stack())
            watchdog_error(notify_message)

        return response
示例#22
0
文件: views.py 项目: chengdg/weizoom
def award_prize(request, id):
	RedEnvelopeRecord.objects.filter(id=id).update(is_awarded=True, awarded_at=datetime.today())
	try:
		return HttpResponseRedirect(request.META['HTTP_REFERER'])
	except:
		notify_msg = u"HTTP_REFERER cause:\n{}".format(unicode_full_stack())
		watchdog_error(notify_msg)
		return HttpResponseRedirect("/market_tools/red_envelope/")
    def handle(self, **options):
        """
        取消“团购”超时的未付款订单的
        """
        try:
            webapp_ids = []
            relations = mall_models.OrderHasGroup.objects.filter(
                group_status=mall_models.GROUP_STATUS_ON)
            for relation in relations:
                if relation.webapp_id not in webapp_ids:
                    webapp_ids.append(relation.webapp_id)

            webapp_id2user = dict([
                (user_profile.webapp_id, user_profile.user)
                for user_profile in UserProfile.objects.filter(
                    webapp_id__in=webapp_ids)
            ])
            order_ids = []
            orders = mall_models.Order.objects.filter(
                order_id__in=[r.order_id for r in relations],
                status=mall_models.ORDER_STATUS_NOT,
                created_at__lte=datetime.now() - timedelta(minutes=15))
            for order in orders:
                try:
                    update_order_status(webapp_id2user[order.webapp_id],
                                        'cancel', order)
                    relations.filter(order_id=order.order_id).update(
                        group_status=mall_models.GROUP_STATUS_failure)
                    logging.info(u"团购15分钟未支付订单order_id:%s取消成功" %
                                 order.order_id)
                    order_ids.append(order.order_id)
                except:
                    notify_msg = u"团购未支付订单{},取消失败, cause:\n{}".format(
                        order.order_id, unicode_full_stack())
                    watchdog_error(notify_msg)
                    continue
            watchdog_info({
                'hint': 'cancel_group_order_and_notify_pay',
                'order_ids': 'order_ids',
                'uuid': 'cancel_group_order_and_notify_pay'
            })
            if not settings.IS_UNDER_BDD and order_ids:
                # BDD时不发消息
                topic_name = "order-close"
                data = {
                    "name": "cancel_group_order_and_notify_pay",
                    "data": {
                        "order_ids": order_ids
                    }
                }
                msg_name = "cancel_order"
                msgutil.send_message(topic_name, msg_name, data)
        except:
            notify_msg = u"团购未支付订单取消失败, cause:\n{}".format(
                unicode_full_stack())
            watchdog_error(notify_msg)

        print "success"
示例#24
0
	def _parse_result(self, result):
		data = dict()
		for attribute in result.split('&'):
			try:
				attr = attribute.split('=')
				data[attr[0]] = attr[1]
			except:
				notify_message = u'解析QQ获取的access token失败,url:{},原因:{}'.format(result, unicode_full_stack())
				watchdog_error(notify_message)
		return data
示例#25
0
    def _poll_response(self):
        """
		发送快递100 订阅请求,返回成功与否信息
		"""
        # post中的param的json
        param_json_data = {
            self.express_params.COMPANY: self.express_company_name,
            self.express_params.NUMBER: self.express_number,
            self.express_params.TO: self.area,
            self.express_params.KEY: self.express_config.app_key,
            self.express_params.PARAMETERS: {
                self.express_params.CALLBACK_URL: self._get_api()
            }
        }
        # 将PARAMETERS的json转换为字符串
        param_str = json.dumps(param_json_data)

        json_data = {
            self.express_params.SCHEMA: self.express_config.schema,
            self.express_params.PARAM: param_str
        }

        # print param_str
        verified_result = ''
        try:
            param_data = urllib.urlencode(json_data)
            # print '-------------------------------------------'
            # print param_data

            if settings.IS_UNDER_BDD:
                from test.bdd_util import WeappClient
                bdd_client = WeappClient()
                response = bdd_client.post(
                    '/tools/api/express/test_kuaidi_poll/?code=1',
                    param_json_data)
                verified_result = response.content

            else:
                request = urllib2.Request(self.express_config.get_api_url(),
                                          param_data)
                response = urllib2.urlopen(request)
                verified_result = response.read()

            watchdog_info(
                u"发送快递100 订阅请求 url: {},/n param_data: {}, /n response: {}".
                format(self.express_config.get_api_url(), param_str,
                       verified_result.decode('utf-8')),
                type=self.express_config.watchdog_type)
        except:
            watchdog_error(u'发送快递100 订阅请求 失败,url:{},data:{},原因:{}'.format(
                self.express_config.get_api_url(), param_str,
                unicode_full_stack()),
                           type=self.express_config.watchdog_type)

        return verified_result
示例#26
0
文件: views.py 项目: chengdg/weizoom
def __get_member_orders(member):
	if member is None:
		return None

	webapp_user = WebAppUser.from_member(member)
	if webapp_user is None:
		notify_message = u"获取会员对应webappuser失败,member id:{}".format(member.id)
		watchdog_error(notify_message)
		return None
	
	return Order.by_webapp_user_id(webapp_user.id).order_by("-created_at")
示例#27
0
文件: views.py 项目: chengdg/weizoom
def __get_member_ship_info(member):
	if member is None:
		return None

	webapp_user = WebAppUser.from_member(member)
	if webapp_user is None:
		notify_message = u"获取会员对应webappuser失败,member id:{}".format(member.id)
		watchdog_error(notify_message)
		return None

	return webapp_user.ship_info
示例#28
0
    def process_request(self, request):
        try:
            if is_request_for_webapp_api(request) and (
                    "member_subscribed_status" in request.get_full_path()
                    or "shopping_cart_count" in request.get_full_path()
                    or "member_product_info" in request.get_full_path()):
                print ">>>>>>>iWebappPageMallMiddleware:", request.get_full_path(
                )
                if "shopping_cart_count" in request.get_full_path():
                    # if webapp_user_id:
                    try:
                        if request.user.is_authenticated():
                            shopping_cart_count = 0
                        else:
                            webapp_user_id = request.webapp_user.id
                            from mall.models import ShoppingCart
                            shopping_cart = ShoppingCart.objects.filter(
                                webapp_user_id=webapp_user_id)
                            if shopping_cart.count() > 0:
                                shopping_cart_count = shopping_cart.count()
                            else:
                                shopping_cart_count = 0
                    except:
                        #notify_message = u"购物车数量函数出错,cause:\n{}".format(unicode_full_stack())
                        #watchdog_error(notify_message)
                        shopping_cart_count = 0

                    print ">>>>>>>shopping_cart_count:", shopping_cart_count
                    response = create_response(200)
                    response.data = {'count': shopping_cart_count}
                    return response.get_response()
                elif "member_subscribed_status" in request.get_full_path():
                    try:
                        if request.user.is_authenticated():
                            is_subscribed = True
                        else:
                            is_subscribed = request.member.is_subscribed
                        response = create_response(200)
                        response.data = {'is_subscribed': is_subscribed}
                        return response.get_response()
                    except:
                        #notify_message = u"获取会员状态失败,cause:\n{},{}".format(unicode_full_stack(),request.COOKIES)
                        #watchdog_error(notify_message)
                        response = create_response(200)
                        response.data = {'is_subscribed': True}
                        return response.get_response()
                elif "member_product_info" in request.get_full_path():
                    from mall import module_api as mall_api
                    return mall_api.get_member_product_info(request)
        except:
            notify_message = u"MemberCacheMiddleware 微首页函数出错,cause:\n{}".format(
                unicode_full_stack())
            watchdog_error(notify_message)
            return None
示例#29
0
 def increase_integral_for_father_by_binding_id(binding_id, webapp_id):
     try:
         member, settings = get_increase_member_and_integral_settings(
             binding_id, webapp_id)
         if member and settings:
             increase_member_integral(member, settings.binding_for_father,
                                      u'好友奖励')
     except:
         notify_msg = u"绑定成功后给上级节点增加积分,cause:\n{}".format(
             unicode_full_stack())
         watchdog_error(notify_msg)
示例#30
0
def create_inactive_account(request):
    username = request.POST.get('name', None)
    key = request.POST.get('key', None)

    if username is None:
        response = create_response(400)
        response.errMsg = u'非法参数'
        return response.get_response()

    if KEY != key:
        response = create_response(INVALID_KEY_ERROR_CODE)
        response.errMsg = u'非法的key'
        return response.get_response()

    exist_users = User.objects.filter(username=username)
    if exist_users.count() == 0:
        response = create_response(400)
        response.errMsg = u'该用户不存在'
        return response.get_response()

    to_operate_user = exist_users[0]
    user_profile = UserProfile.objects.get(user=to_operate_user)

    try:
        #首先更改用户名,改为:${username}_id_deleted
        #该用户名之后,原用户就无法登录
        to_operate_user.username = "******".format(
            to_operate_user.username, to_operate_user.id)
        to_operate_user.save()

        user_profile.is_mp_registered = False
        user_profile.force_logout()

        #进行接触绑定操作
        mpuser = get_system_user_binded_mpuser(to_operate_user)
        if mpuser:
            mpuser.delete()

        #删除所有之前的会员
        Member.objects.filter(webapp_id=user_profile.webapp_id).delete()
        #删除所有之前的微信用户
        WeixinUser.objects.filter(webapp_id=user_profile.webapp_id).delete()

        response = create_response(200)
    except:
        error_msg = u"置用户({}}失效操作失败, cause:\n{}".format(
            username, unicode_full_stack())
        watchdog_error(error_msg)

        response = create_response(500)
        response.innerErrMsg = error_msg

    return response.get_response()