def get(self, request, format=None): Tool.param_in_options(request, 'file_type', ['image']) file_type = request.query_params.get('file_type', 'image') bucket_name = QiniuServe.get_bucket_name(file_type) token = QiniuServe.gen_app_upload_token(bucket_name) data = {'token': token} return Response(Tool.format_data(data))
def post(self, request): """登录""" required_params = ['account', 'password'] Tool.required_params(request, required_params) username = request.data.get('account') password = request.data.get('password') try: user = authenticate(self.request, username=username, password=password) if user: customer_login.login(request, user) data = { 'id': user.customer.id, 'user_id': user.id, 'name': user.customer.name, 'im_token': user.customer.im_token, } mm_CustomerPoint.add_action(request.session['customer_id'], mm_CustomerPoint.Action_Login) return Response(Tool.format_data(data)) else: raise LoginException('账号或密码错误') except User.DoesNotExist: raise LoginException('账号不存在')
class Controller(object): def __init__(self): # 获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name') def kill_server(self): mac = '''ps -ef|grep appium|grep -v grep|grep %s|awk '{print "kill -9 " $2}'|sh''' % self.port win = 'taskkill /F /IM node.exe /t' subprocess.getoutput(win) def start_server(self): self.kill_server() command = 'appium -a {ip} -p {port} -U {deviceName}'.format( ip=self.device.get('ip'), port=self.device.get('port'), deviceName=self.device.get('deviceName')) print('command : %s' % command) subprocess.Popen(command, stdout=open(SYSTEMPATH, 'a+'), stderr=open(ERRORPATH, 'a+'), shell=True) def test_server(self): # mac = 'ps -ef|grep appium|grep -v grep|grep %s' % self.port win = 'netstat -ano | findstr %s' % self.port time.sleep(3) while True: data = subprocess.getoutput(win) if data: time.sleep(10) print('%s 端口启动成功。' % self.port) break else: print('%s 端口启动失败。5秒后重试。' % self.port) time.sleep(5) return True def start_driver(self): url = 'http://{ip}:{port}/wd/hub'.format(ip=self.device.get('ip'), port=self.port) # 合并手机信息和包名入口 self.device.update(self.tester) driver = webdriver.Remote(url, self.device) driver_queue.put(driver)
def post(self, request): required_params = ['code', 'account', 'password'] Tool.required_params(request, required_params) code = request.data.get('code') account = request.data.get('account') password = request.data.get('password') mm_SMSCode.is_effective(account, code) customer = mm_Customer.add(account, password) customer_login.login(request, customer.user) data = dict(account=account, id=customer.id, user_id=customer.user.id) return Response(Tool.format_data(data), status=status.HTTP_200_OK)
def __init__(self): # 获取配置信息 self.config = Tool().get_config self.tester = self.config.get('tester') self.device_type = self.config.get('device_type') # 获取到所有的手机信息 self.devices = self.config.get('devices') self.device = self.devices.get(self.device_type)[0] # port 用于校验服务是否启动 self.port = self.device.get('port') self.name = self.device.get('name')
def create(self, request, *args, **kwargs): Tool.required_params(request, ['account']) account = request.data.get('account') code = gen_code() if not mm_SMSCode.can_get_new_code(tel=account): raise SMSExcecption('请过几分钟尝试') response = send_simple_code(account, code) if response['Code'] == 'OK': mm_SMSCode.add(account, code) return Response(Tool.format_data()) else: raise SMSExcecption(response['Message'])
def post(self, request): """密码重置""" if request.user.is_authenticated: Tool.required_params(request, ['raw_password', 'new_password']) raw_password = request.data['raw_password'] new_password = request.data['new_password'] user = mm_Customer.reset_password_by_login(request.user.id, raw_password, new_password) else: account = request.data.get('account') password = request.data.get('password') code = request.data.get('code') user = mm_Customer.reset_password_by_sms(account, password, code) return Response(Tool.format_data(), status=status.HTTP_200_OK)
def customer_around(self, latitude, longitude, gender, distance=10000): latitude_range, longitude_range = Tool.get_lon_lat_range(latitude, longitude, distance) latitude_low, latitude_heigh = latitude_range longitude_low, longitude_heigh = longitude_range params = { 'latitude_low': latitude_low, 'latitude_heigh': latitude_heigh, 'longitude_low': longitude_low, 'longitude_heigh': longitude_heigh, 'distance': distance, 'latitude': latitude, 'longitude': longitude, 'gender': gender } sql = ''' Select *, st_distance_sphere(POINT({longitude}, {latitude} ), POINT(lv_customers.longitude, lv_customers.latitude)) AS distance FROM lv_customers WHERE id >= 1 AND lv_customers.gender != {gender} AND lv_customers.latitude BETWEEN {latitude_low} AND {latitude_heigh} AND lv_customers.longitude BETWEEN {longitude_low} AND {longitude_heigh} HAVING distance < {distance} ORDER BY distance; '''.format(**params) return mm_Customer.raw(sql)
def post(self, request, *args, **kwargs): data = request.data.dict() data['customer_id'] = request.session['customer_id'] serializer = self.get_serializer_class()(data=data) serializer.is_valid(raise_exception=True) serializer.save() return Response(Tool.format_data(serializer.data, msg=messages.ADD_OK))
def delete(self, request, *args, **kwargs): with transaction.atomic(): comment = self.get_object() comment.is_del = True comment.save() comment.moment.modify_comment_total(-1) return Response(Tool.format_data(msg=messages.DELETE_COMMENT_OK))
def post(self, request, format=None): _name = request.user.customer.name _avatar_url = request.user.customer.avatar_url if 'condition' in request.data: required_fields = [ 'age_range', 'height_range', 'profession', 'education', 'income', 'marital_status', 'child_status', 'years_to_marry' ] for key in required_fields: if key not in json.loads(request.data.get('condition')): return Response(data={'detail': 'condition缺少字段或格式错误'}, status=status.HTTP_400_BAD_REQUEST) serializer = CustomerSerializer(request.user.customer, data=request.data, partial=True) if serializer.is_valid(raise_exception=True): if 'avatar_url' in serializer.validated_data: serializer.validated_data[ 'avatar_url'] = serializer.validated_data['avatar_url'] avatar_url = serializer.validated_data.pop('avatar_url') serializer.validated_data['avatar_status'] = 0 mm_Picture.add_picture(request.user.customer.id, avatar_url) serializer.save() if any([ not _name == serializer.data['name'], not _avatar_url == serializer.data['avatar_url'] ]): IMServe.refresh_token(request.user.customer.id, request.user.customer.name, request.user.customer.avatar_url) return Response(Tool.format_data(serializer.data)) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def get(self, request, format=None): data = IMServe.gen_token(request.user.customer.id, request.user.customer.name, request.user.customer.avatar_url) request.user.customer.im_token = data['token'] request.user.customer.save() return Response(Tool.format_data(data))
def post(self, request, *args, **kwargs): topic = mm_Topic.get_toptics(request.data.get('name'), request.session['customer_id'], request.user.id, request.data.get('logo_url')) serializer = self.serializer_class(topic) return Response(Tool.format_data(serializer.data))
def get(self, request): BASE_USER_COUNT = 1000 user_total = cache.get(CacheKey.user_total) if user_total is None: user_total = mm_Customer.all().count() cache.set(CacheKey.user_total, user_total, 60 * 5) user_total += BASE_USER_COUNT app_config = { 'version': '1.0.3', 'url': 'http://pkqiei3s2.bkt.clouddn.com/app-release-xueqiu', 'desc': '修复图片显示问题,更换雪球logo', 'music': 'http://oys4026ng.bkt.clouddn.com/musiclight.mp3', 'user_total': user_total, 'image_domain': QiNiuSettings.BUCKET_DOMAIN_DICT['image'], 'chat_times_limit': settings.NORNAML_CUSTOMER_CHAT_TIMES_LIMIT_PER_DAY, 'kefuid': mm_Customer.get_kefu_id(), 'isNeedVerified': handan_global_config.IsNeedVerified, 'next_app_version': handan_global_config.Next_APP_Version, 'version_ios': handan_global_config.CURRENT_APP_VERSION_IOS, 'version_android': handan_global_config.CURRENT_APP_VERSION_ANDROID, } return Response(Tool.format_data(app_config))
def post(self, request, format=None): customer_id = request.data['customer_id'] relationship_status = int( request.data.get('status', RELATIONSHIP_FOLLOWING)) relationship = request.user.customer.add_relationship( customer_id, relationship_status) serializer = BaseRelationShipSerializer(relationship) return Response(Tool.format_data(serializer.data))
def update(self, request, *args, **kwargs): certification = self.get_object() if certification.status == mm_Certification.Status_Verified: data = {'detail': '已通过审核禁止修改'} return Response(data=data, status=status.HTTP_400_BAD_REQUEST) else: serializers = self.serializer_class(certification, data=request.data, partial=True) serializers.is_valid(raise_exception=True) serializers.save() return Response(Tool.format_data(data=serializers.data))
def post(self, request, *args, **kwargs): data = request.data.dict() data['customer_id'] = self.request.session['customer_id'] serializer = self.serializer_class(data=data) serializer.is_valid(raise_exception=True) try: serializer.save() return Response(Tool.format_data(msg=messages.ADD_OK)) except IntegrityError: raise DBException('请勿重复提交') except: msg = traceback.format_exc() raise DBException(msg)
def post(self, request, *args, **kwargs): with transaction.atomic(): like, created = mm_Likes.get_or_create( customer_id=request.session['customer_id'], moment_id=kwargs['pk']) if created: like.moment.modify_like_total() mm_Notice.add_notice(like.moment, like, Action.ACTION_TYPE_ADD_LIKE) mm_CustomerPoint.add_action(request.session['customer_id'], mm_CustomerPoint.Action_Add_Like) serializer = LikeCreateSerializer(like) return Response( Tool.format_data(serializer.data, msg=messages.ADD_LIKE_OK))
def post(self, request, *args, **kwargs): data = request.data.dict() data['moment_id'] = kwargs['pk'] data['from_customer_id'] = request.session['customer_id'] serializer = CommentSerializer(data=data) if serializer.is_valid(raise_exception=True): with transaction.atomic(): comment = serializer.save() comment.moment.comment.add(comment) comment.moment.modify_comment_total() mm_Notice.add_notice(comment.moment, comment, Action.ACTION_TYPE_ADD_COMMENT) mm_CustomerPoint.add_action( request.session['customer_id'], mm_CustomerPoint.Action_Add_Comment) return Response(Tool.format_data(msg=messages.ADD_COMMENT_OK))
def post(self, request, *args, **kwargs): data = request.data.dict() comment = self.get_object() data['moment_id'] = comment.moment_id data['from_customer_id'] = request.session['customer_id'] data['to_customer_id'] = comment.from_customer_id if comment.from_customer_id == data['from_customer_id']: # 自己回复自己当做新评论 data['reply_to_id'] = None else: data['reply_to_id'] = kwargs['pk'] serializer = CommentSerializer(data=data) if serializer.is_valid(raise_exception=True): with transaction.atomic(): comment = serializer.save() comment.moment.comment.add(comment) comment.moment.modify_comment_total() mm_Notice.add_notice(comment.moment, comment, Action.ACTION_TYPE_ADD_REPLY) return Response(Tool.format_data(msg=messages.REPLY_COMMENT_OK))
def create(self, request, *args, **kwargs): data = request.data.dict() topics_str = data.pop('topics', '') topic_list = [] if topics_str: topic_tags = re.findall(r'#.*?#', topics_str) for tag in topic_tags: name = tag.replace('#', '') topic = mm_Topic.get_toptics(name, request.user.customer.id, request.user.id) topic_list.append(topic) data['topic'] = topic_list data['customer_id'] = request.user.customer.id serializer = MomentsCreateSerializer(data=data) serializer.is_valid(raise_exception=True) moment = serializer.save() mm_CustomerPoint.add_action(request.session['customer_id'], mm_CustomerPoint.Action_Add_Moment) for t in topic_list: moment.topic.add(t) return Response(Tool.format_data(serializer.data))
def delete(self, request, format=None): customer_id = request.query_params.get('customer_id', 0) request.user.customer.remove_relationship(customer_id) return Response(Tool.format_data())
def get(self, request): logout(request) return Response(Tool.format_data(), status=status.HTTP_200_OK)
def update(self, request, *args, **kwargs): notice = self.get_object() notice.status = NoticeStatus.STATUS_READ notice.save() return Response(Tool.format_data())
def delete(self, request, *args, **kwargs): with transaction.atomic(): like = self.get_object() like.moment.modify_like_total(-1) like.delete() return Response(Tool.format_data(msg=messages.DELETE_LIKE_OK))
def _generate_report(self, result): rows = [] sortedResult = self.sortResult(result.result) for cid, (cls, cls_results) in enumerate(sortedResult): # subtotal for a class np = nf = ne = 0 for n, t, o, e in cls_results: if n == 0: np += 1 elif n == 1: nf += 1 else: ne += 1 # format class description if cls.__module__ == "__main__": name = cls.__name__ else: name = "%s.%s" % (cls.__module__, cls.__name__) doc = cls.__doc__ and cls.__doc__.split("\n")[0] or "" desc = doc and '%s: %s' % (name, doc) or name row = self.REPORT_CLASS_TMPL % dict( style=ne > 0 and 'errorClass' or nf > 0 and 'failClass' or 'passClass', desc=desc, count=np + nf + ne, Pass=np, fail=nf, error=ne, cid='c%s' % (cid + 1), ) rows.append(row) from lib.tools import Tool import os pnglist = Tool().app_error_picture() if len(pnglist) > 0: Rewrite_results = [] for cls_p in cls_results: name = cls_p[1].id().split('.')[-1] for png in pnglist: png_name = png[0].split('.')[2] png_name = png_name.split('/')[-1] if png_name == name: tmp = cls_p + png Rewrite_results.append(tmp) break else: tmp = cls_p + ('',) Rewrite_results.append(tmp) for tid, (n, t, o, e, png) in enumerate(Rewrite_results): self._generate_report_test(rows, cid, tid, n, t, o, e, png) else: for tid, (n, t, o, e) in enumerate(cls_results): self._generate_report_test(rows, cid, tid, n, t, o, e) report = self.REPORT_TMPL % dict( test_list=''.join(rows), count=str(result.success_count + result.failure_count + result.error_count), Pass=str(result.success_count), fail=str(result.failure_count), error=str(result.error_count), ) return report
def destroy(self, request, *args, **kwargs): obj = self.get_object() IMServe.leave_group(request.user.customer.id, obj.id) return Response(Tool.format_data(msg=messages.LEAVE_GROUP_OK))
def retrieve(self, request, *args, **kwargs): obj = self.get_object() IMServe.join_group(request.user.customer.id, obj.id, obj.name) return Response(Tool.format_data(msg=messages.JOIN_GROUP_OK))
def get(self, request): data = {'unread_count': self._get_unread_count()} return Response(Tool.format_data(data))
def setUpClass(cls): cls.page = Page() cls.tool = Tool() # 重点!!! 每次测试之前需要删除报错的截图,不然成功的用例也会将错误图片放进去 cls.tool.clear_picture()