Пример #1
0
def search(page=1):
    keywords = request.args.get("keywords", '').strip()

    if not keywords:
        return redirect(url_for("home.index"))

    s = Search.query.filter_by(words=keywords).first()
    if s:
        #org.update({"words":keywords, "times":org.times + 1 })
        s.times = s.times + 1
        s.save()
    else:
        n = Search()
        n.words = keywords
        n.times = 1
        n.save()

    page_obj = Post.query.search(keywords).as_list().\
        paginate(page, per_page=Post.PER_PAGE)
    if page_obj.total == 1:
        post = page_obj.items[0]
        return redirect(post.url)
    page_url = lambda page: url_for(
        'home.search', page=page, keywords=keywords)

    return render_template("home/search.html",
                           page_obj=page_obj,
                           page_url=page_url,
                           keywords=keywords)
Пример #2
0
    def search(
        self,
        location: Optional[str] = None,
        language: Optional[str] = None,
        fulltime: bool = False,
    ) -> Dict:
        req_params = {
            "location": f'"{location}"' if location else None,
            "description": f'"{language}"' if language else None,
            "full_time": f"on" if fulltime else None,
            "utf8": "✓",
        }

        res = REQUESTS.get(f"https://jobs.github.com/positions.json", params=req_params)

        jobs = None

        if res.status_code == 200:
            jobs = res.json()

        search_data = {
            "location": location,
            "description": language,
            "full_time": fulltime,
            "ip_address": request.remote_addr,
        }

        search = Search(**search_data)
        search.save(commit=True)

        return self.schema.dump(jobs, many=True)
Пример #3
0
def resources(request):

    zipcode = request.POST.get('zipcode')
    resource = request.POST.get('resource')

    if not zipcode and not resource:
        return render(request, 'resources.html')

    if zipcode and resource:
        # Save the search
        search = Search(**{
                'zipcode': zipcode,
                'resource': resource
            })
        search.save()

    try:
        zipcode = int(zipcode[:5])

        # Zero-pad New England zipcodes
        if len(str(zipcode)) == 4:
            zipcode = '0{0}'.format(zipcode)
    except:
        messages.error(request, "Sorry, I didn't recognize that zipcode. Please try again.")
        return HttpResponseRedirect('/app/resources')
    else:
        try:
            zipcode_coords = ZipcodeCoordinates.objects.get(zipcode=zipcode)
        except:
            # If this zipcode has not yet been searched, create a new one
            zipcode_coords = ZipcodeCoordinates(zipcode=zipcode)
            zipcode_coords.save()

    try:
        resource = Resource.objects.get(name=resource.lower())
    except:
        messages.error(request, "Please choose a resource and try again.")
        return HttpResponseRedirect('/app/resources')
    else:
        locations = Location.objects.select_related('provider').filter(
            resources_available=resource).exclude(provider__approved=False)
        within_radius = []
        for location in locations:
            if vincenty(
                (location.latitude, location.longitude), 
                (zipcode_coords.latitude, zipcode_coords.longitude)
            ).miles <= RADIUS_DISTANCE:
                within_radius.append(location)

    context = {
        'within_radius': within_radius,
        'zipcode': zipcode,
        'resource': resource,
        'search_from': zipcode_coords,
    }

    return render(request, 'resources.html', dictionary=context)
Пример #4
0
def search_items(context, request):
    """
    Method to handle item search.
    Validates SearchForm from GET request, persists the search specifics and returns context with item table.
    """
    if request.method != 'GET':
        context['form'] = SearchForm()
        return render(request, 'app/index.html', context)

    form = SearchForm(request.GET)
    if not form.is_valid():
        return render(request, 'app/index.html', context)
    what = form.cleaned_data['what'].strip()
    place = form.cleaned_data['place']
    location = form.cleaned_data['location']
    category = form.cleaned_data['category']

    search = None
    if what or category or place or location:
        search_data = form.cleaned_data
        if request.user.is_authenticated():
            search_data['user'] = request.user
        search = Search(**search_data)
        search.save()
        context['searched'] = True

    # Cannot repopulate location field. Google places api js populates it based on the place field.
    form = SearchForm(data=dict(what=what, place=place, category=category))
    context['form'] = form

    # Search
    items = Item.objects.filter(is_published=True)
    if category:
        items = items.filter(categories=category)
    if what:
        # items = items.annotate(what=SearchVector('name', 'description'))
        items = items.filter(
            Q(name__icontains=what) | Q(description__icontains=what))

    # Create table from results
    table = None
    if items and search and search.location:
        found_items = []
        for item in items:
            found_item = FoundItem(item=item, search=search)
            found_item.distance = distance(item.location, location).miles
            found_item.save()
            found_items.append(found_item)
            table = FoundItemTable(found_items)
    elif items:
        table = ItemTable(items)

    if table:
        RequestConfig(request).configure(table)
        context['table'] = table
    return context
Пример #5
0
def resources(request, **kwargs):
    searched_location = request.POST.get('location')
    resource = request.POST.getlist('resource')
    type_ = request.POST.get('type')
    radius = request.POST.get('radius')

    if not type_:
        type_ = request.GET.get('type')

    if not type_:
        type_ = kwargs.get('type')

    try:
        radius = int(radius)
        assert 10 < radius < 150
    except:
        radius = RADIUS_DISTANCE

    if not searched_location and not resource: # neither
        return render(request, 'resources.html', { 'type': type_ })
    elif searched_location and resource: # both
        # Save the search
        search = Search(**{
                'location': searched_location,
                'resource': resource
            })
        search.save()

        coords = find_search_coordinates(searched_location)
    elif not searched_location:
        coords = False

    if not coords:
        cdnt_find_loc_error_msg = _("Sorry, I couldn't find that location. Please try again. You can also search by city or by zipcode.")
        messages.error(request, cdnt_find_loc_error_msg)
        if type_:
            return HttpResponseRedirect(reverse('resources', kwargs={'type': type_}))
        else:
            return HttpResponseRedirect(reverse('resources'))

    try:
        if len(resource) == 1:
            resource = [Resource.objects.get(name=resource[0].lower())]
        elif len(resource) > 1:
            resource = Resource.objects.filter(name__in=[res.lower() for res in resource])
        else:
            raise ValueError
    except:
        cdnt_find_res_error_msg = _("Please choose a resource and try again.")
        messages.error(request, cdnt_find_res_error_msg)
        if type_:
            return HttpResponseRedirect(reverse('resources', kwargs={'type': type_}))
        else:
            return HttpResponseRedirect(reverse('resources'))
    else:
        locations = Location.objects.select_related('provider').exclude(provider__approved=False)

        if len(resource) == 1: # Just one resource chosen
            locations = locations.filter(resources_available=resource[0])
        elif len(resource) > 1:
            locations = locations.filter(resources_available__in=resource)
            
        preferred_orgs = False
        within_radius = []
        for location in locations:
            dist = vincenty(
                (location.latitude, location.longitude), 
                (coords['latitude'], coords['longitude'])
            ).miles
            if dist <= radius:
                within_radius.append((location,round(dist,1)))
                if location.provider.preferred:
                    preferred_orgs = True

        within_radius.sort(key=lambda tup: (not(tup[0].provider.preferred), tup[1]))
        #sorts the location/distance tuples by dist with preferred ones first
        
        
        #passing a sorted list of tuples with (orgname, distance)
        

    context = {
        'within_radius': within_radius,
        'radius':radius,
        'preferred_orgs':preferred_orgs,
        'location': searched_location,
        'resource': resource,
        'search_from': coords,
        'type': type_
    }

    return render(request, 'resources.html', dictionary=context)
Пример #6
0
def resources(request):

    searched_location = request.POST.get('location')
    resource = request.POST.get('resource')

    if not searched_location and not resource:
        return render(request, 'resources.html')

    if searched_location and resource:
        # Save the search
        search = Search(**{
                'location': searched_location,
                'resource': resource
            })
        search.save()

    coords = False

    try:
        searched_location = int(searched_location[:5])

        # Zero-pad New England zipcodes
        if len(str(searched_location)) == 4:
            searched_location = '0{0}'.format(searched_location)
    except:
        try:
            geolocator = GoogleV3()
            address, (latitude, longitude) = geolocator.geocode(searched_location)
        except:
            pass
        else:
            coords = {
                'latitude': latitude,
                'longitude': longitude,
            }
    else:
        try:
            zipcode_coords = ZipcodeCoordinates.objects.get(zipcode=searched_location)
        except:
            # If this zipcode has not yet been searched, create a new one
            zipcode_coords = ZipcodeCoordinates(zipcode=searched_location)
            zipcode_coords.save()
        finally:
            coords = {
                'latitude': zipcode_coords.latitude,
                'longitude': zipcode_coords.longitude
            }

    if not coords:
        messages.error(request, "Sorry, I couldn't find that location. Please try again. You can also search by city or by zipcode.")
        return HttpResponseRedirect('/app/resources')

    try:
        resource = Resource.objects.get(name=resource.lower())
    except:
        messages.error(request, "Please choose a resource and try again.")
        return HttpResponseRedirect('/app/resources')
    else:
        locations = Location.objects.select_related('provider').filter(
            resources_available=resource).exclude(provider__approved=False)
        within_radius = []
        for location in locations:
            if vincenty(
                (location.latitude, location.longitude), 
                (coords['latitude'], coords['longitude'])
            ).miles <= RADIUS_DISTANCE:
                within_radius.append(location)

    context = {
        'within_radius': within_radius,
        'location': searched_location,
        'resource': resource,
        'search_from': coords,
    }

    print context

    return render(request, 'resources.html', dictionary=context)
Пример #7
0
def resources(request):
    searched_location = request.POST.get('location')
    resource = request.POST.get('resource')

    if not searched_location and not resource:
        return render(request, 'resources.html')

    if searched_location and resource:
        # Save the search
        search = Search(**{
            'location': searched_location,
            'resource': resource
        })
        search.save()

    coords = False

    try:
        searched_location = int(searched_location[:5])

        # Zero-pad New England zipcodes
        if len(str(searched_location)) == 4:
            searched_location = '0{0}'.format(searched_location)
    except:
        try:
            geolocator = GoogleV3()
            address, (latitude,
                      longitude) = geolocator.geocode(searched_location)
        except:
            pass
        else:
            coords = {
                'latitude': latitude,
                'longitude': longitude,
            }
    else:
        try:
            zipcode_coords = ZipcodeCoordinates.objects.get(
                zipcode=searched_location)
        except:
            # If this zipcode has not yet been searched, create a new one
            zipcode_coords = ZipcodeCoordinates(zipcode=searched_location)
            zipcode_coords.save()
        finally:
            coords = {
                'latitude': zipcode_coords.latitude,
                'longitude': zipcode_coords.longitude
            }

    if not coords:
        messages.error(
            request,
            "Sorry, I couldn't find that location. Please try again. You can also search by city or by zipcode."
        )
        return HttpResponseRedirect('/app/resources')

    try:
        resource = Resource.objects.get(name=resource.lower())
    except:
        messages.error(request, "Please choose a resource and try again.")
        return HttpResponseRedirect('/app/resources')
    else:
        locations = Location.objects.select_related('provider').filter(
            resources_available=resource).exclude(provider__approved=False)
        within_radius = []
        for location in locations:
            if vincenty((location.latitude, location.longitude),
                        (coords['latitude'],
                         coords['longitude'])).miles <= RADIUS_DISTANCE:
                within_radius.append(location)

    context = {
        'within_radius': within_radius,
        'location': searched_location,
        'resource': resource,
        'search_from': coords,
    }

    print context

    return render(request, 'resources.html', dictionary=context)