예제 #1
0
def search_product(request):
    query = request.GET.get('query')

    # s = ProductDocument.search().query("match", name=query)
    # qs = s.to_queryset()

    p = MultiMatch(query=query, fields=['query', 'name'], fuzziness='AUTO')
    s = ProductDocument.search().query(p)
    qs = s.to_queryset()
    # response = s.execute()

    if query is not None:
        return Response([obj.get_obj() for obj in qs]).get_obj()
    else:
        return Response(400, 'Search query invalid')
예제 #2
0
 async def check(  # pylint: disable=arguments-differ
         self,
         session: ClientSession,
         *,
         url: str = None,
         **kwargs: Any) -> Response:
     """
     Fetching page HTML
     """
     if not url:
         raise TypeError("url doen not set")
     start = now()
     try:
         response = await session.get(url, headers=self.headers)
     except asyncio.TimeoutError:
         logger.warning("cannot reach {}, host does not respond (timeout)",
                        url)
         return Response(
             url,
             error="host does not respond (timeout)",
             status_code=-1,
             load_time=0,
             request_time=now(),
             body=None,
         )
     except aiohttp.ClientError as err:
         logger.warning("cannot reach {}, {}", url, err)
         return Response(
             url,
             error=f"{err}",
             status_code=-1,
             load_time=0,
             request_time=now(),
             body=None,
         )
     load_time = (now() - start).total_seconds()
     logger.debug("{} returns {} -- {}", url, response.status, load_time)
     body = await response.text()
     return Response(
         url,
         error=None
         if response.ok else f"returns {response.status} response",
         status_code=response.status,
         load_time=load_time,
         request_time=now(),
         body=body,
     )
예제 #3
0
def search_supplier(request):
    query = request.GET.get('query')

    s = ProductDocument.search().query("match", name=query)
    qs = s.to_queryset()

    # from elasticsearch_dsl.query import Q
    # p = Q("multi_match", query=query, fields=['name','category__name', 'supplier__name'],
    #                 type='phrase_prefix')
    # s = ProductDocument.search().query(p)
    # qs = s.to_queryset()
    # result = s.execute()

    if query is not None:
        return Response([obj.get_obj() for obj in qs]).get_obj()
    else:
        return Response(400, 'Search query invalid')
예제 #4
0
def get_product(request):
    name = request.GET.get('name')

    if name is not None:
        return Response([
            obj.get_obj()
            for obj in Product.objects.filter(name__contains=name)
        ]).get_obj()
    else:
        return JsonResponse({'code': 400, 'message': 'Search query invalid'})
예제 #5
0
def test_model():
    request_time = now()
    obj = Response(
        url="https://google.com",
        error=None,
        status_code=200,
        load_time=0.23,
        request_time=request_time,
        body=None,
    )
    assert obj.ok
    assert obj.to_dict()["url"] == "https://google.com"
    assert obj.to_dict()["load_time"] == 0.23

    assert isinstance(obj.json_dumps(), str)

    error_status = Response(
        url="https://google.com",
        error="error_500",
        status_code=500,
        load_time=0.23,
        request_time=now(),
        body=None,
    )
    assert not error_status.ok
예제 #6
0
 def __call__(
     self, serialized: bytes, *args: Any, **kwargs: Any
 ) -> Optional[Response]:
     try:
         raw_data = json.loads(serialized)
     except JSONDecodeError as error:
         logger.error(
             "receive invalid json object, error: {}".format(serialized, str(error))
         )
         return
     try:
         data = self.document_schema.check(raw_data)
     except t.DataError as err:
         logger.error("invalid document structure object, {}", err)
         return
     return Response(**data)
예제 #7
0
def done(request):
    '''Process a survey submission

    This view proceseses a potential new volunteer's survey results and registers them
    as a new volunteer. It provides the new volunteer confirmation that they have succesfully
    navigated the process of signing up.
    '''
    if request.method != 'POST':
        return render(request, 'core/done.html', {'volunteer_name': 'luis'})
        return redirect('volunteer_listing')

    volunteer_name = request.POST.get('volunteer_name', '')
    volunteer_email = request.POST.get('volunteer_email', '')
    volunteer_phone = request.POST.get('volunteer_phone', '')

    volunteer = Volunteer()
    volunteer.name = volunteer_name
    volunteer.email = volunteer_email
    volunteer.phone = volunteer_phone
    volunteer.save()

    params = {'volunteer_name': volunteer.name}

    for key, value in request.POST.items():
        match = re.search(r'^q(\d+)$', key)
        if match and value:
            match = int(match.group(1))
            question = get_object_or_404(Question, pk=match)

            response = Response()
            response.volunteer = volunteer
            response.question = question
            response.answer = value
            response.save()

    return render(request, 'core/done.html', params)