def list(self, request): datasets = Job.objects.values_list('ci_dataset', flat=True).distinct() return response.Response(datasets)
def _get(self, request, rest_of_world=False, original_region=None, *args, **kwargs): es = FeedItemIndexer.get_es() # Parse region. if rest_of_world: region = mkt.regions.RESTOFWORLD.id else: region = request.REGION.id # Parse carrier. carrier = None q = request.QUERY_PARAMS if q.get('carrier') and q['carrier'] in mkt.carriers.CARRIER_MAP: carrier = mkt.carriers.CARRIER_MAP[q['carrier']].id # Fetch FeedItems. sq = self.get_es_feed_query(FeedItemIndexer.search(using=es), region=region, carrier=carrier, original_region=original_region) # The paginator triggers the ES request. with statsd.timer('mkt.feed.view.feed_query'): feed_items = self.paginate_queryset(sq) feed_ok = self._check_empty_feed(feed_items, rest_of_world) if feed_ok != 1: return self._handle_empty_feed(feed_ok, region, request, args, kwargs) # Build the meta object. meta = mkt.api.paginator.CustomPaginationSerializer( feed_items, context={'request': request}).data['meta'] # Set up serializer context. feed_element_map = { feed.FEED_TYPE_APP: {}, feed.FEED_TYPE_BRAND: {}, feed.FEED_TYPE_COLL: {}, feed.FEED_TYPE_SHELF: {}, } # Fetch feed elements to attach to FeedItems later. apps = [] sq = self.get_es_feed_element_query( Search(using=es, index=self.get_feed_element_index()), feed_items) with statsd.timer('mkt.feed.view.feed_element_query'): feed_elements = sq.execute().hits for feed_elm in feed_elements: # Store the feed elements to attach to FeedItems later. feed_element_map[feed_elm['item_type']][feed_elm['id']] = feed_elm # Store the apps to retrieve later. apps += self.get_app_ids(feed_elm) # Remove dupes from apps list. apps = list(set(apps)) # Fetch apps to attach to feed elements later. app_map = self.get_apps(request, apps) # Super serialize. with statsd.timer('mkt.feed.view.serialize'): feed_items = FeedItemESSerializer(feed_items, many=True, context={ 'app_map': app_map, 'feed_element_map': feed_element_map, 'request': request }).data # Filter excluded apps. If there are feed items that have all their # apps excluded, they will be removed from the feed. feed_items = self.filter_feed_items(request, feed_items) feed_ok = self._check_empty_feed(feed_items, rest_of_world) if feed_ok != 1: if not rest_of_world: log.warning('Feed empty for region {0}. Requerying feed with ' 'region=RESTOFWORLD'.format(region)) return self._handle_empty_feed(feed_ok, region, request, args, kwargs) return response.Response({'meta': meta, 'objects': feed_items}, status=status.HTTP_200_OK)
def get(self, request): qs = models.Notice.objects.all() # 因为对象不止一个,序列化[obj,obj,obj]这种,要使用many=True serializer = basic.NoticeSerializer(qs, many=True) return response.Response({'status': 0, 'data': serializer.data})
def action(self, serializer): setattr(self.request.user, User.USERNAME_FIELD, serializer.data['new_' + User.USERNAME_FIELD]) self.request.user.save() return response.Response(status=status.HTTP_204_NO_CONTENT)
def ret_testpaper_detail(request, testpaper_id): if request.method == "GET": context = {} single_selections = [] multiple_selections = [] judgment_selections = [] analysis_questions = [] testpaper_id = int(testpaper_id) testpaper = capability_models.TestPaper.objects.get(id=testpaper_id) context['name'] = testpaper.name context['number'] = testpaper.task_number context['allScore'] = testpaper.task_all_score taskArrary = TestPaperTask.objects.filter(test_paper=testpaper) rows = [] for t in taskArrary: task = get_task_object(t.task_hash) rows.append(Serializer(task, t).data) context['tasks'] = rows for task in context["tasks"]: if task.has_key("is_choice_question"): if _judgment_question_type( task["hash"] ) == theory_models.ChoiceTask.TopicProblem.SINGLE: single_selections.append(task) elif _judgment_question_type( task["hash"] ) == theory_models.ChoiceTask.TopicProblem.MULTIPLE: multiple_selections.append(task) else: judgment_selections.append(task) else: analysis_questions.append(task) tasks = dict(judgment_selections=judgment_selections, single_selections=single_selections, multiple_selections=multiple_selections, analysis_questions=analysis_questions) context['tasks'] = tasks return response.Response({'error_code': 0, 'response_data': context}) elif request.method == "POST": name = request.data['examname'] if int(testpaper_id) == 0 and TestPaper.objects.filter( name=name).exists(): return response.Response({'error_code': 1}) questions = request.data['questions'] list = questions.values() list.sort(key=lambda k: (k.get('qorder', 0))) number = 0 allScore = 0 for questions in list: number = number + 1 allScore = allScore + int(questions['score']) event_teachers = request.data.get('teacher') if int(testpaper_id) > 0: testPaper = TestPaper.objects.get(id=testpaper_id) testPaper.name = name testPaper.task_number = number testPaper.task_all_score = allScore testPaper.teacher = ",".join( event_teachers) if event_teachers else None testPaper.save() tpt = TestPaperTask.objects.filter(test_paper=testPaper) for t in tpt: t.delete() else: testPaper = TestPaper.objects.create( name=name, task_number=number, task_all_score=allScore, create_time=timezone.now(), create_user=request.user, public=True, ) for questions in list: TestPaperTask.objects.create(test_paper=testPaper, task_hash=questions['hash'], score=questions['score']) cache = CacheProduct( "%s-%s" % (TestPaperViewSet.__module__, TestPaperViewSet.__name__)) delete_cache(cache) return response.Response({'error_code': 1})
def get(self, request, *args, **kwargs): auth.logout(request) response_data = { 'message': _('Logged out successfully'), } return response.Response(response_data, status=status.HTTP_200_OK)
def action(self, serializer): for user in self.get_users(serializer.data['email']): self.send_email(**self.get_send_email_kwargs(user)) return response.Response(status=status.HTTP_204_NO_CONTENT)
def response_created(data): return response.Response(data, status.HTTP_201_CREATED)
def post(self, request, *args, **kwargs): post_id = kwargs.pop('id') if not post_id: return response.Response({}) jar = requests.cookies.RequestsCookieJar() authorization_key = requests.post( "https://refugee-info.ghost.io/ghost/api/v0.1/authentication/token", data=AUTH_REQUEST, cookies=jar).json() auth_headers = { 'Authorization': "Bearer {}".format(authorization_key['access_token']) } post_response = requests.get("{}/{}/?status=all".format( POSTS_URL, post_id), headers=auth_headers, cookies=jar) tags = requests.get("{}/?status=all&limit=1000".format(TAGS_URL), headers=auth_headers, cookies=jar).json()['tags'] print(tags, auth_headers, post_response) tag_map = {} t_en = [o for o in tags if o['slug'] == 'english'] if t_en: tag_map['en'] = t_en for k, v in settings.GHOST_TAG_MAP.items(): t = [o for o in tags if o['slug'] == v] if t: tag_map[k] = t if post_response.status_code == 200: post_list = post_response.json() post_en = post_list['posts'][0] info = utils.get_blog_transifex_info(post_en['slug']) for k, v in info.items(): if k == 'en' or v['completed'] != '100%': continue translated = utils.pull_blog_from_transifex(post_en['slug'], k) translated['tags'] = [tag_map[k] for k in tag_map] if k in tag_map: translated['tags'] = tag_map[k] b = requests.get("{}/slug/{}/?status=all".format( POSTS_URL, translated['slug']), headers=auth_headers) if b.status_code == 404: r = requests.post( POSTS_URL + '/', data=json.dumps({"posts": [translated]}), headers={ **{ 'Content-Type': 'application/json', }, **auth_headers }, cookies=jar) print({"posts": [translated]}, '\n\n\n') print(r.status_code, r.text) else: possible_posts = b.json() post_to_be_edited = possible_posts['posts'][0] r = requests.put( "{}/{}/".format(POSTS_URL, post_to_be_edited['id']), data=json.dumps({"posts": [translated]}), headers={ **{ 'Content-Type': 'application/json', }, **auth_headers }, cookies=jar) print({"posts": [translated]}, '\n\n\n') print(r.status_code, r.text) return response.Response(info) return response.Response({})
def get_paginated_response(self, data): return response.Response(OrderedDict([ ('total', self.count), ('rows', data) ]))
def response_validation_error(error): return response.Response(error, status.HTTP_400_BAD_REQUEST)
def action(self, serializer): self.request.user.set_password(serializer.data['new_password']) self.request.user.save() return response.Response(status=status.HTTP_200_OK)
def list(self, request): stats = self.get_stats() return response.Response(stats)
def list(self, request): defaults = self.get_defaults() return response.Response(defaults)
def reset_token(self, request: request.Request, id: str, **kwargs) -> response.Response: team = self.get_object() team.api_token = generate_random_token() team.save() return response.Response(TeamSerializer(team).data)
def patch(self, request, *args, **kwargs): course = self.get_object() self.remove_handgraders(course, request.data['remove_handgraders']) return response.Response(status=status.HTTP_204_NO_CONTENT)
def schema_view(request): generator = schemas.SchemaGenerator(title='REST DEMO', patterns=[], url='/restdemo/') return response.Response(generator.get_schema())
def post(self, request, *args, **kwargs): result = UserService.login(request) return response.Response(result, status=status.HTTP_202_ACCEPTED)
def schema_view(request): generator = schemas.SchemaGenerator(title='PadLock APIs') return response.Response(generator.get_schema(request=request))
def delete(self, request, *args, **kwargs): UserService.logout(request) return response.Response('', status=status.HTTP_204_NO_CONTENT)
def action(self, serializer): serializer.user.set_password(serializer.data['new_password']) serializer.user.save() return response.Response(status=status.HTTP_204_NO_CONTENT)
def monumenten_schema_view(request): generator = schemas.SchemaGenerator(title='Geo Endpoints', patterns=urlpatterns) return response.Response(generator.get_schema(request=request))
def post(self, request): Token.objects.filter(user=request.user).delete() user_logged_out.send(sender=request.user.__class__, request=request, user=request.user) return response.Response(status=status.HTTP_204_NO_CONTENT)
def get(self, request): result: dict = {"result": True} quarter: str = self.request.GET.get("quarter") if utils.get_quarter_by_date(quarter) == 0: result["result"] = False return response.Response(result, status.HTTP_200_OK)
def list(self, request, *args, **kwargs): page = self.paginate_queryset( self.filter_queryset(self.get_queryset())) serializer = self.get_pagination_serializer(page) return response.Response(serializer.data)
def get(self, request, *args, **kwargs): filters = [] for filter in settings.ENABLED_MOBILE_FILTERS: if filter == 'difficulty' and DifficultyLevel.objects.exists(): filters.append({ "id": "difficulty", "type": "contains", "showAllLabel": _("Show all difficulties"), "hideAllLabel": _("Hide all difficulties") }) if filter == 'lengths': filters.append({ "id": "lengths", "type": "interval", "showAllLabel": _("Show all lengths"), "hideAllLabel": _("Hide all lengths") }) if filter == 'ascent': filters.append({ "id": "ascent", "type": "interval", "showAllLabel": _("Show all ascents"), "hideAllLabel": _("Hide all ascents") }) if filter == 'districts' and District.objects.exists(): filters.append({ "id": "districts", "type": "contains", "showAllLabel": _("Show all districts"), "hideAllLabel": _("Hide all districts") }) if filter == 'cities' and City.objects.exists(): filters.append({ "id": "cities", "type": "contains", "showAllLabel": _("Show all cities"), "hideAllLabel": _("Hide all cities") }) if filter == 'accessibilities' and Accessibility.objects.exists(): filters.append({ "id": "accessibilities", "type": "contains", "showAllLabel": _("Show all accessibilities"), "hideAllLabel": _("Hide all accessibilities") }) if filter == 'practice' and Practice.objects.exists(): filters.append({ "id": "practice", "type": "contains", "showAllLabel": _("Show all practices"), "hideAllLabel": _("Hide all practices") }) if filter == 'durations': filters.append({ "id": "durations", "type": "interval", "showAllLabel": _("Show all durations"), "hideAllLabel": _("Hide all durations") }) if filter == 'themes' and Theme.objects.exists(): filters.append({ "id": "themes", "type": "contains", "showAllLabel": _("Show all themes"), "hideAllLabel": _("Hide all themes") }) if filter == 'route' and Route.objects.exists(): filters.append({ "id": "route", "type": "contains", "showAllLabel": _("Show all routes"), "hideAllLabel": _("Hide all routes") }) return response.Response({ 'filters': filters, 'data': [ { 'id': 'length', 'name': _('Length'), 'values': settings.MOBILE_LENGTH_INTERVALS, }, { 'id': 'ascent', 'name': _('Ascent'), 'values': settings.MOBILE_ASCENT_INTERVALS, }, { 'id': 'duration', 'name': _('Duration'), 'values': settings.MOBILE_DURATION_INTERVALS, }, { 'id': 'difficulty', 'name': _('Difficulty'), 'values': api_serializers.DifficultySerializer( DifficultyLevel.objects.all().order_by('pk'), many=True, context={ 'request': request }).data }, { 'id': 'practice', 'name': _('Practice'), 'values': api_serializers.PracticeSerializer( Practice.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'accessibilities', 'name': _('Accessibilities'), 'values': api_serializers.AccessibilitySerializer( Accessibility.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'route', 'name': _('Route'), 'values': api_serializers.RouteSerializer( Route.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'themes', 'name': _('Themes'), 'values': api_serializers.ThemeSerializer( Theme.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'networks', 'name': _('Networks'), 'values': api_serializers.NetworkSerializer( TrekNetwork.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'information_desk_types', 'name': _('Information Desks Types'), 'values': api_serializers.InformationDeskTypeSerializer( InformationDeskType.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'districts', 'name': _('Districts'), 'values': api_serializers.DistrictSerializer( District.objects.all().order_by('pk'), many=True, context={ 'request': request }).data }, { 'id': 'cities', 'name': _('Cities'), 'values': api_serializers.CitySerializer( City.objects.all().order_by('pk'), many=True, context={ 'request': request }).data }, { 'id': 'poi_types', 'name': _('POI types'), 'values': api_serializers.POITypeSerializer( POIType.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'touristiccontent_types', 'name': _('Touristic content types'), 'values': api_serializers.TouristicContentTypeSerializer( TouristicContentType.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'touristicevent_types', 'name': _('Touristic event types'), 'values': api_serializers.TouristicEventTypeSerializer( TouristicEventType.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, { 'id': 'touristiccontent_categories', 'name': _('Touristic event types'), 'values': api_serializers.TouristicContentCategorySerializer( TouristicContentCategory.objects.all().order_by('pk'), many=True, context={ 'request': request }).data, }, ] })
def schema_view(request): """ Swagger documentation """ generator = schemas.SchemaGenerator(title='Draftboard API') return response.Response(generator.get_schema(request=request))
def listroute(self, request, *args, **kwargs): routes = "https://roads.googleapis.com/v1/snapToRoads?path=-35.27801,149.12958|-35.28032,149.12907|-35.28099,149.12929|-35.28144,149.12984|-35.28194,149.13003|-35.28282,149.12956|-35.28302,149.12881|-35.28473,149.12836&interpolate=true&key=AIzaSyBYCfS1nBZ-Ff6CRZ87Wclu6_ckGFRhlAQ" req = requests.get(routes) return response.Response(req.json())
def list(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = self.get_serializer(queryset, many=True) return response.Response({'status': 0, 'data': serializer.data})
def schema_view(request): generator = schemas.SchemaGenerator(title='Documentación del API de Proyectos de ley.') return response.Response(generator.get_schema(request=request))