Example #1
0
def	List(request):

    try:
	user = GetUserKod(request)
    except:
	return HttpResponseRedirect('/')


    ### --- Удаление файла ---
    if request.method == 'GET':
	try:
	    delete_id = request.GET['delete_file']
	    DelFile(delete_id)
	except:
	    pass


    ### --- Получение номера страницы ---
    try:
	page = int(request.GET.get('page',1))
	request.session['page'] = page
    except:
	pass
	
    try:
	page = int(request.session['page'])
    except:
	page = 1



    try:
	search = request.session['search']
    except:
	search = ''



    if request.method == 'POST':
	
	form = SearchForm(request.POST)
	if form.is_valid():
	    search = form.cleaned_data['search']
	    request.session['search'] = search

    data = ListFile(user,search)


    paginator = Paginator(data,50)
    try:
	data_page = paginator.page(page)
    except (EmptyPage, InvalidPage):
	data_page = paginator.page(paginator.num_pages)

    form = SearchForm(None)
    form.fields['search'].initial = search

    c = RequestContext(request,{'data':data_page,'form':form})
    c.update(csrf(request))
    return render_to_response("userfiles/list.html",c)
Example #2
0
def index_view(request):
    search_form = SearchForm()
    bugs = Bugs.objects
    if request.method == "GET":
        search_form = SearchForm(request.GET)
        if search_form.is_valid():
            search = search_form.cleaned_data["search_text"]
            status = search_form.cleaned_data["status"]
            issue_types = search_form.cleaned_data["issue_types"]
            product = search_form.cleaned_data["product"]
            priority = search_form.cleaned_data["priority"]
            keyword = search_form.cleaned_data["keyword"]

            bugs = bugs.filter(short_desc__icontains=search) | \
                    bugs.filter(longdescs__thetext__icontains=search)
            bugs = bugs.distinct()
            if status != "":
                bugs = bugs.filter(bug_status__exact=status)
            if priority != "":
                bugs = bugs.filter(priority__exact=priority)
            if product:
                bugs = bugs.filter(product__name__exact=product)
            if keyword:
                bugs = bugs.filter(kws__id__exact=keyword)
            if issue_types == 1:
                bugs = bugs.exclude(bug_status__in=["CLOSED", "RESOLVED"])
    bugs = bugs.order_by("bug_id").reverse()
    return render_to_response("index.html", {
        "bugs": bugs,
        "search_form": search_form,
        },
        context_instance=RequestContext(request))
Example #3
0
def search(request):
    """
    On post, recieve a string and radius, geocode, and return a bunch of
    buddies within that radius
    """
    # prevent access by non-organisations
    try:
        organisation = request.user.organisation.all()[0]
    except IndexError:
        return HttpResponseForbidden()
    
    form = SearchForm(request.POST or None)
    if form.is_valid():
        buddies_in_range = []
        # geocode address
        lat, lng = geocode(request.POST.get('location'))
        # to keep things super simple, pull out all buddies, then filter in
        # memory. obviously this will have to be fixed once there is a
        # non-trivial number of buddies in the db. and when we have more 
        # than a day to work on this thing
        buddies = Buddy.objects.all()
        for buddy in buddies:
            buddy_lat, buddy_lng = float(buddy.location['latitude']), float(buddy.location['longitude'])
            radius = int(request.POST.get('radius'))
            dist = points2distance(((buddy_lng, 0, 0), (buddy_lat, 0, 0)),((lng, 0, 0), (lat, 0, 0)))
            if dist <= radius:
                buddies_in_range.append(buddy)
    else:
        buddies_in_range = None
        
    return render_to_response('buddies/search.html', {
        'form': form,
        'buddies_in_range': buddies_in_range,
        'is_get': request.method == 'GET'
    }, context_instance=RequestContext(request))
Example #4
0
def index():
    # logic for the edit my profile page
    # pull text from input fields and rewrite JSON entry in the DB associated with that profile
    form = SearchForm()
    if form.validate_on_submit():
	# creating dictionary to store text from input text fields
        s = {}
	for i in ['Profname','about','age','email','phone','loc','empid','school','gradYear','involv', 'picture', 'groupd']:
	    if request.form[i] != "":
		s[i] = request.form[i]
	    else:
		s[i] = ''
	s['inter'] = {}
	s['username'] = current_user.username
	for i in ['exploring', 'nightlife', 'outdoors', 'sports', 'videogames']:
	    if i in request.form.getlist('interests'):
		s['inter'][i] = 1
	    else:	
		s['inter'][i] = 0
	#converting dictionary to JSON
	json_string = json.dumps(s)
	#checking if a profile with the username already exists in the db
	result = db_connection.execute("""SELECT p.comment_id, p.doc FROM user_profile p WHERE p.doc.username = :x""", x=current_user.username).fetchone()[0] 
	if result:
	    this_profile = UserProfile.get(result)
	    this_profile.doc = json_string
	    db.session.commit()
	else:
	    db.session.add(UserProfile(json_string))
	    db.session.commit()
	return redirect(url_for('viewprof', username = current_user.username))
    return render_template('index.html', form=form)
Example #5
0
def events():
    form = SearchForm(request.forms.decode())
    # XXX: make WTForm for this and validate!

    if form.validate():
        filters = {}
        if form.country.data != "":
            filters['country'] = form.country.data

        session = create_session()
        matching_events = session.query(Event).filter_by(**filters).\
            order_by(Event.start_date)

        print "--------------------"
        print form.yob.data
        print form.yob is None
        if form.yob is not None:
            print form['yob']
            matching_events = ((matching_events)
                .filter(form.yob.data <= Event.max_yob) #1985 <= 2000
                .filter(form.yob.data >= Event.min_yob)) #1985 >= 1980


        e = list(matching_events)
        return dict(events=e, get_url=app.get_url)
    return dict(events=[], error="nothing found", get_url=app.get_url)
Example #6
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        results = wiki.search(form.term.data, form.ignore_case.data)
        return render_template('search.html', form=form,
                               results=results, search=form.term.data)
    return render_template('search.html', form=form, search=None)
Example #7
0
def search():
    form = SearchForm()
    if form.validate_on_submit():
        longitude, latitude, city = geosearch.get_geo_loc_twice(form.location.data)
        results = models.get_venues_by_bounding_box(latitude, longitude)
        return render_template('search.html', results=results, form=form)
    return render_template('search.html', form=form, results=None)
Example #8
0
def search():
    form1 = SearchForm()
    m = []
    entries = {}
    message = None
    if form1.validate_on_submit():
    	keywords = form1.query.data
    	  #parse the HTTP response
        m = searchWord(keywords)

    elif request.form.get("like") != None:
        smallURL = request.form.get("small")
        bigURL = request.form.get("big")
        message = LikeImage(smallURL, bigURL)
        return message

    elif request.form.get("review") != None:
        entries = reviewLiked()
        
    elif request.form.get("dislike") != None:
        smallURL = request.form.get("small")
        bigURL = request.form.get("big")
        dislikeImage(smallURL, bigURL)
        entries = reviewLiked()
    return render_template('search.html',
        title = 'Flickr Search',
        form1 = form1,
        liked = entries,
        imgs = m,
        message = message)
Example #9
0
def test_search(request, code):
    invitation = check_invitation(code)
    if not invitation:
        messages.error(request, 'Your personal URL is incorrect, please reset your account or provide proper url')
        return redirect('index') 
    
    results={}
    from forms import SearchForm
    if request.method == 'POST':
        form = SearchForm(request.POST) 
        if form.is_valid(): 
            keywords = __to_keywords(form.cleaned_data['search'])
            for k in keywords:
                profiles = Profile.objects.filter(keywords=k)
                for p in profiles:
                    count = results.get(p, 0)
                    results[p]=count+1
            if len(results)==0:
                messages.error(request, "Sorry, we couldn't find match for you. Try later.")
    
    else:
        form=SearchForm()
    
    return render_to_response('researchers/test_search.html', {'key':code, 
                                                                'form':form, 
                                                                'results':results,
                                                                'sorted':sorted(results.items(), key=lambda x: -x[1])},  context_instance=RequestContext(request))
Example #10
0
def home(request):
    """ Manages our home page.  If a POST request is received, then
    we're going to pull the search value out and attempt to filter
    for it.  This can be a hash or a plaintext value.
    """
    
    if request.method == 'POST':
        form = SearchForm(request.POST)

        if form.is_valid():
            data =  HashModel.objects.all()
            search = request.POST.get("search_input")

            # search the hashval and plaintext fields 
            result = data.filter(Q(hashval=search) | Q(plaintext=search))

            return render_to_response('home.html',
                            {'form':SearchForm(),
                             'results':result
                            },
                            context_instance=RequestContext(request))

    return render_to_response("home.html", 
                                {'form' : SearchForm(),
                                 'results':HashModel.objects.all()[:50]
                                },
                                context_instance=RequestContext(request))
Example #11
0
def main(key_id=0, act=""):
    user_obj = User()
    tran_obj = Transaction()
    key_obj = Key()
    search_form = SearchForm()
    keys = user_obj.list_all_key(current_user.role, current_user.company_id)
    if request.method == "POST":
        if act == "take":
            selected_key = key_obj.query.get(key_id)
            selected_key.available = False
            db.session.add(selected_key)
            new_transaction = Transaction(user=current_user, key_id=key_id, time_stamp=datetime.datetime.now() + timedelta(hours=3))
            db.session.add(new_transaction)
            db.session.commit()
            flash("Key Taken")
            return redirect(url_for('main'))
        elif act == "release":
            selected_key = key_obj.query.get(key_id)
            selected_key.available = True
            db.session.add(selected_key)
            db.session.commit()
            flash("Key Release")
            return redirect(url_for('main'))
    if search_form.validate_on_submit():
        print search_form.key_input.data
        string_input = search_form.key_input.data
        if string_input == "":
            flash("Please enter something for searching")
            return redirect(url_for("main"))
        else:
            return redirect(url_for('search', input=string_input))
    elif request.method == "GET":
        return render_template("main.html", keys=keys, search_form=search_form)
Example #12
0
def raw_email(stype,docnumber):
	#Get the raw email from the database
	db_name = '01_database/hrc.sqlite'
	db = sqlite3.connect(db_name)
	cursor = db.cursor()

	#search = docnumber
	sql_cmd = 'SELECT RawText FROM emails\
		   WHERE DocNumber IS ?'
	cursor.execute(sql_cmd, (docnumber,))
	tmp = cursor.fetchone()
	raw_email = tmp[0]
	#Remove special characters and split into lines:
	evec = raw_email.split('\n')
	for line in evec:
		line.strip()
	#Take care of search form
	form = SearchForm()
	if form.validate_on_submit():# and request.method == 'POST':
		flash('Searching Hillary\'s emails for "%s"' % 
              	(form.search.data ))
		#stype as placeholder in case we want to add different seach schemes
		#'bs' = body/subject
		#'ps' = people search 
		#'es' = email search (to/from address)
        	return redirect(url_for('.search', stype = stype, search = form.search.data))

	return render_template('raw_email.html',
				raw_email = evec,
				docnumber = docnumber,
				form = form)
def search(request, term=None):
    form = search_term = result_list = results = None
    if request.POST:
        form = SearchForm(request.POST)
        if form.is_valid():
            search_term = form.cleaned_data['terms']
    if term is not None:
        # Note, we might need to do some cleanup here
        search_term = term
    if search_term is not None:
        # Get results
        result_list = BaseStop.search(search_term)

        paginator = Paginator(result_list, 25)
        page = request.GET.get('page', 1)
        try:
            results = paginator.page(page)
        except PageNotAnInteger:
            # If page is not an integer, deliver first page.
            results = paginator.page(1)
        except EmptyPage:
            # If page is out of range (e.g. 9999), deliver last page of results.
            results = paginator.page(paginator.num_pages)
    if form is None:
        form = SearchForm()

    return render(request, 'stops/results.html', {
        'results': results,
        'term': search_term,
        'form': form
    })
Example #14
0
def book(book_id):
    form = SearchForm()
    book = Book.query.filter_by(id = book_id).first()
    pics = Picture.query.filter_by(book_id = book_id).order_by(Picture.order)
    if book == None:
        flash('Book not found')
        return redirect(url_for('index'))

    if form.validate_on_submit():
        api = InstagramAPI(client_id=app.config['INSTAGRAM_ID'], client_secret = app.config['INSTAGRAM_SECRET'])
        # if max_tag_id > 0:
        #     if request.args['query']:
        #         tag_name = request.args['query']
        #     tag_media, next = api.tag_recent_media(count = 20, max_id = max_tag_id, tag_name = request.args['query'])
        # else:
        tag_media, next = api.tag_recent_media(count = 20, tag_name = form.query.data)
        instagram_results = []
        for media in tag_media:
            instagram_results.append(media.images['thumbnail'].url)
        try:
            max_tag_id = next.split('&')[2].split('max_tag_id=')[1]
        except: 
            max_tag_id = None
        return render_template('book.html',
            query = form.query.data,
            instagram_results = tag_media,
            pics = pics,
            form = form,
            next = max_tag_id,
            book = book)

    return render_template('book.html',
        book = book,
        pics = pics,
        form = form)
Example #15
0
def search_form(request,queryset,Model):
    if request.method =="POST":
        form = SearchForm(request.POST)

        if form.is_valid():
            search = str(form.cleaned_data['search']).lower()
            results = list()
            #Loop over object in queryset of model
            for object in queryset:
                model_dict = model_to_dict(object)
                print (model_dict)

                #Check if the searched string is included in one of the Object field
                """
                for key in model_dict:
                    print('Searching: ')
                    print (model_dict[key])
                """

                if search in str(model_dict['name']):
                        #Add the users id in a list
                        print('I found d')
                        results.append(object.id)
                        break
            #Re-initialize the model queryset filtering by found objects.id
            queryset = Model.objects.filter(pk__in = (results))


    else:
        form = SearchForm()
        queryset = Model.objects.all()

    return queryset
Example #16
0
def search(request):
    
    def make_tups(list, name='None'):
        tup = (('None', '%s' % name),)
        for item in list:
            tup = tup + ((item, item),)
        return tup

    poller_choices = make_tups(Poller.objects.all().values_list('name', flat=True).order_by('name'), 'Pollers')
    server_choices = make_tups(Server.objects.all().values_list('name', flat=True).order_by('name'), 'Servers')

    if request.method == 'POST':
        form = SearchForm(request.POST, poller_choices=poller_choices, server_choices=server_choices)
        if form.is_valid():
            data = form.cleaned_data

            transfers = TransferLog.objects.all().order_by('-started')
            if data['server'] != 'None':
                transfers = transfers.filter(server__exact=data['server']).order_by('-started')
            if data['poller'] != 'None':
                transfers = transfers.filter(name__exact=data['poller']).order_by('-started')
            if data['status'] != 'None':
                transfers = transfers.filter(status__exact=data['status']).order_by('-started')
            if data['filename'] != '':
                transfers = transfers.filter(filename__icontains=data['filename']).order_by('-started')

            return render(request, 'dispatch_web/search.html', {'form': form, 'transfers': transfers})

    else:
        form = SearchForm(poller_choices=poller_choices, server_choices=server_choices)

    return render(request, 'dispatch_web/search.html', {'form': form})
Example #17
0
def	List(request):

    try:
	if CheckAccess(request,'23') != 'OK':
	    return render_to_response("mtmc/notaccess/mtmc.html")
    except:
	return HttpResponseRedirect('/')




    if request.method == 'POST':
	formuser = UserForm(request.POST)
	if formuser.is_valid():
	    user = formuser.cleaned_data['user']
	    request.session['user_id'] = user

	formsearch = SearchForm(request.POST)
	if formsearch.is_valid():
	    search = formsearch.cleaned_data['search']
	    r = FindKey(search)
	    if len(r) == 1:
		return HttpResponseRedirect('/mtmcedit/?eq_id=%s' % search)

    ### --- Сохранное занчение user_id ---
    try:
	user_id = request.session['user_id']
    except:
	user_id = ''

    try:
	print_ok = request.GET['print']
	response = HttpResponse(content_type='application/pdf')
	response['Content-Disposition'] = 'attachment; filename="list.pdf"'
	buff = StringIO()
	result = PrintForm(buff,user_id)
	response.write(result.getvalue())
	buff.close()
	return response
    except:
	pass



    formmove = MoveForm(None)
    formsearch = SearchForm(None)
    formuser = UserForm(None)
    formuser.fields['user'].initial = user_id


    data = GetList(user_id)

    if len(data)!=0 and user_id != 'ALL':
	print_ok = True
    else:
	print_ok = False

    c = RequestContext(request,{'data':data,'formuser':formuser,'formsearch':formsearch,'formmove':formmove,'print_ok':print_ok})
    c.update(csrf(request))
    return render_to_response("mtmc/list.html",c)
Example #18
0
def search():
    """ Search form """
    search = SearchForm()
    if search.validate_on_submit():
        return redirect(url_for('.search_results', query=search.search.data))
    else:
        return redirect(request.referrer)
Example #19
0
def check_in(request):
    form = SearchForm(request.GET or None)
    members = orchestras = None

    if form.is_valid():
        term = form.cleaned_data.get('q')
        members = (Member.objects.filter(Q(first_name__istartswith=term) |
                                         Q(last_name__istartswith=term) |
                                         Q(pid__contains=term))
                   .select_related('orchestras')
                   .order_by('first_name', 'last_name'))

        if len(members) == 1:
            member = members[0]
            return redirect('check_in_list',
                            token=member.orchestras.all()[0].token, member_pk=member.pk)

        orchestras = Orchestra.objects.filter(Q(orchestra_name__icontains=term) |
                                              Q(short_name__icontains=term))

        if len(orchestras) == 1:
            return redirect('check_in_list', token=orchestras[0].token)

        for member in members:
            member.orchestra_token = member.orchestras.all()[0].token

    return render(request, 'orkester/search.html',
                  {'form': form, 'members': members, 'orchestras': orchestras})
Example #20
0
def search(request):
    did_post_pun = ""
    if request.method == "POST":
        form, did_post_pun = process_pun_form(request)
    else:
        form = PunForm()
    context_dict = {"new_pun_form": form, "search_form": SearchForm()}
    query_string = ""
    puns = Pun.objects.all()

    search_form = SearchForm(request.GET)
    if search_form.is_valid():
        data = search_form.cleaned_data
        query_string = data["search"]
        puns = watson.filter(Pun, query_string)
    if puns is not None:
        puns = order_query_set_by_pun_score(puns)
        for pun in puns:
            pun.profile = UserProfile.objects.get(user=pun.owner)
    if request.user.is_authenticated():
        puns = set_up_down_votes(request, puns)
        profile = UserProfile.objects.get(user=request.user)
        if not profile.show_nsfw:
            puns = [pun for pun in puns if pun.NSFW == False]
    context_dict["tags_list"] = get_all_tags_list()
    context_dict["query_string"] = query_string
    context_dict["puns"] = puns
    response = render_to_response("punny/search-results.html", context_dict, context_instance=RequestContext(request))
    if did_post_pun is True:
        response.set_cookie("success", "pun posted!", max_age=3)
    elif did_post_pun is False:
        response.set_cookie("failed", "post failed", max_age=3)
    return response
Example #21
0
def account_view(request):
    context = {}
    context['user'] = request.user
    # Search
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if request.user.is_authenticated():
            if form.is_valid():
                search = Search.objects.create(
                    url=form.cleaned_data['url'],
                    title=form.cleaned_data['title'],
                    owner=request.user)
                search.save()
                # redirect to proper search
                return redirect(reverse('search'))
            else:
                # return form errors
                return render_to_response('account.html', context, RequestContext(request))
        else:
            # permissions should make this impossible
            return render_to_response('account.html', context, RequestContext(request))
    context['search_form'] = SearchForm()
    # context['searches'] = Search.objects.filter(owner=request.user).all()
    context['searches'] = Search.objects.all()
    for search in Search.objects.all():
        print search.created
    return render_to_response('account.html', context, RequestContext(request))
Example #22
0
def search():
    form = SearchForm(request.form)
    articles = None
    if form.validate() and request.method == 'POST':
        title = form.title.data
        articles = Article.query.filter(Article.deleted == False, Article.raw_content.contains(title)).order_by(Article.id.desc())

    return render_template('common/search.html', articles=articles)
Example #23
0
def course():
    if request.method == 'GET':
        return render_template('admin/courselist.html')
    form = SearchForm(request.form)
    if form.validate():
        sres=form.search()
        return render_template('admin/courselist.html',result=sres)
    return render_template('admin/courselist.html')
def search(request):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            return HttpResponse(stream_response(
                request.POST['url'],
                request.POST['depth'],
                request.POST['search']), mimetype='text/html')
Example #25
0
	def test_valid_data(self):
		# valid data is at least 1 input is given

		form = SearchForm({
			'dept_name' : 'Admin'
			})

		self.assertTrue(form.is_valid())
Example #26
0
def search(request):
    """ Поиск пациентов """
    patients_qs = Patient.objects.all()
    form = SearchForm(request.GET)
    special_cure_text = ''
    header = u'Все'
    
    if len(request.GET) == 0:
        # Если поиск не запускали, то и не надо показывать всех пациентов
        return render_to_response('search.html',
                              {'form': form, 'have_search_result': False},
                              context_instance=RequestContext(request))

    
    if form.is_valid():
        full_name = form.cleaned_data.get('full_name')
        if full_name:
            patients_qs = patients_qs.filter(all_full_names__icontains=full_name)
        type_residence = form.cleaned_data.get('type_residence')
        if type_residence:
            patients_qs = patients_qs.filter(type_residence=type_residence)
        social_status = form.cleaned_data.get('social_status')
        if social_status:
            patients_qs = patients_qs.filter(social_status=social_status)
        birthday = form.cleaned_data.get('birthday')
        if birthday:
            patients_qs = patients_qs.filter(birthday=birthday)
        death = form.cleaned_data.get('death')
        if death:
            patients_qs = patients_qs.filter(death=death)
        mo_added = form.cleaned_data.get('mo_added')
        if mo_added:
            patients_qs = patients_qs.filter(visit__is_add=True,
                                             visit__mo=mo_added)
        special_cure = form.cleaned_data.get('special_cure')
        if special_cure:
            if special_cure in HEADER_SEARCH:
                header = HEADER_SEARCH[special_cure]
            patients_qs = patients_qs.filter(special_cure=special_cure)
        diagnosis = form.cleaned_data.get('diagnosis')
        if diagnosis:
            q_st = Q(diagnosis__code__contains=diagnosis) | \
                   Q(diagnosis__name__contains=diagnosis)
            with_diagnosis = patients_qs.filter(diagnosis__code__contains=diagnosis)
            patients_qs = patients_qs.filter(pk__in=with_diagnosis)

    patients_qs = patients_qs.values('pk', 'all_full_names',
                                     'birthday', 'diagnosis_text_code',
                                     'name_allocate_mo', 'gender')
    response = {'patients': patients_qs,
                'count': patients_qs.count(),
                'special_cure_text': special_cure_text,
                'form': form,
                'header': header,
                'have_search_result': True}
    return render_to_response('search.html',
                              response,
                              context_instance=RequestContext(request))
Example #27
0
def xk():
    if request.method == 'GET':
        return render_template('student/xk.html')
    form = SearchForm(request.form)
    #卧槽简直是坑啊,之前在这用wtform一切都没问题尼玛就是获取不到表单数据,索性SearchForm不继承Form,然后就过了,我勒个去,怀疑是wtform哪bug了
    if form.validate():
        sres=form.search()
        return render_template('student/xk.html',result=sres)
    return render_template('student/xk.html')
Example #28
0
def home(request, *arg):
    if request.method == 'POST':
        form = SearchForm(request.POST)
        if form.is_valid():
            pass
    else:
        form = SearchForm()
    c = RequestContext(request, {'form': form})
    return render_to_response('home.html', c)
Example #29
0
def search():
    form = SearchForm(request.form)
    if not form.validate():
        return render_template('search.html', term="", results=None)
    term = request.form['searchfield']
    results = db.session.execute("SELECT * FROM post WHERE to_tsvector(\
        'english', title || ' ' || body) @@ to_tsquery(\
        'english', '" + term + "') ORDER BY timestamp DESC LIMIT 20")
    return render_template('search.html', term=term, results=results)
Example #30
0
	def test_valid_login(self):
		form = SearchForm({
			'dept_name' : 'Admin'
			})

		form.submit()

		response = self.client.get('/')
		self.assertEquals(response.status_code, 200)
Example #31
0
def homepage():
    form= SearchForm()
    if form.validate_on_submit():
        return weatherdata(form.countryname.data)
    return render_template('home.html', form =form,title='Home')
Example #32
0
def search_form(request):
    context = {'search_form': SearchForm()}
    return render(request, 'search_form.html', context)
Example #33
0
def browse():
    form = SearchForm()
    return render_template("browse.html", searchform=form)
Example #34
0
def home():
    form = SearchForm()
    return render_template('home.html', form=form)
Example #35
0
def thread_index(request, mlist_fqdn, threadid, month=None, year=None):
    ''' Displays all the email for a given thread identifier '''
    search_form = SearchForm(auto_id=False)
    store = get_store(request)
    thread = store.get_thread(mlist_fqdn, threadid)
    if not thread:
        raise Http404
    prev_thread, next_thread = store.get_thread_neighbors(mlist_fqdn, threadid)

    sort_mode = request.GET.get("sort", "thread")
    set_message_votes(thread.starting_email, request.user)

    from_url = reverse("thread",
                       kwargs={
                           "mlist_fqdn": mlist_fqdn,
                           "threadid": threadid
                       })
    # Tags
    tag_form = AddTagForm(initial={'from_url': from_url})
    try:
        tags = Tag.objects.filter(threadid=threadid, list_address=mlist_fqdn)
    except Tag.DoesNotExist:
        tags = []

    # Favorites
    fav_action = "add"
    if request.user.is_authenticated():
        try:
            Favorite.objects.get(list_address=mlist_fqdn,
                                 threadid=threadid,
                                 user=request.user)
        except Favorite.DoesNotExist:
            pass
        else:
            fav_action = "rm"

    # Extract relative dates
    today = datetime.date.today()
    days_old = today - thread.starting_email.date.date()
    days_inactive = today - thread.last_email.date.date()

    mlist = store.get_list(mlist_fqdn)
    subject = stripped_subject(mlist, thread.starting_email.subject)

    # TODO: eventually move to a middleware ?
    # http://djangosnippets.org/snippets/1865/
    is_bot = True
    user_agent = request.META.get('HTTP_USER_AGENT', None)
    if user_agent:
        is_bot = robot_detection.is_robot(user_agent)

    context = {
        'mlist': mlist,
        'threadid': threadid,
        'subject': subject,
        'tags': tags,
        'search_form': search_form,
        'addtag_form': tag_form,
        'month': thread.date_active,
        'first_mail': thread.starting_email,
        'neighbors': (prev_thread, next_thread),
        'months_list': get_months(store, mlist.name),
        'days_inactive': days_inactive.days,
        'days_old': days_old.days,
        'sort_mode': sort_mode,
        'fav_action': fav_action,
        'reply_form': ReplyForm(),
        'is_bot': is_bot,
        'participants': thread.participants,
    }
    context["participants"].sort(key=lambda x: x[0].lower())

    if is_bot:
        # Don't rely on AJAX to load the replies
        context["replies"] = _get_thread_replies(request, thread)

    return render(request, "thread.html", context)
Example #36
0
def Search():
    form = SearchForm()
    #item = form.item.data
    #model = form.model.data
    #color = form.color.data
    return render_template("search.html", form=form)
def home():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('search', name=form.username.data))
    return render_template('search.html', form=form)
Example #38
0
def home():
    # form for search in navbar (since this is the same for all routes,
    # except login and register, this should probably be set in the app.py
    # file with other configuration stuff)
    search_form = SearchForm()

    # determine the user
    email = session["user"]
    user = User.query.filter_by(email=email).first()

    #get list of unread books by user and sort it by date_added
    book_list = Book.query.filter_by(user=user.id, read=False).all()
    book_list = sorted(book_list, key=lambda x: x.date_added)
    print(book_list)
    # TODO: add settings table and query for user settings to set theme
    user_theme = "dark-theme"
    all_categories = Category.query.all()
    category_list = []
    cat_styles = {}

    for category in all_categories:
        category_list.append(category.name)

    if user_theme == "light-theme":
        color_list = ["blue", "green", "yellow", "purple", "red", "orange"]

    else:
        color_list = ["blue", "green", "purple", "red", "orange", "yellow"]

    for i in range(0, len(category_list)):

        cat_styles[category_list[i]] = user_theme + "-" + color_list[i]

    print(cat_styles)
    # TODO: replace zipped lists with dictionary of book objects with category and style properties
    # if 3 or fewer books, display all books
    if len(book_list) <= 3:

        book_categories = []
        [
            book_categories.append(
                Category.query.filter_by(id=book.category).first())
            for book in book_list
        ]

        style_list = []

        # would this be better as a list comp? Prob not bc of multiple conditions?
        for category in book_categories:

            style_list.append(cat_styles[category.name])

        # note: need to wrap zip in list in Py 3x bc zip rtns iterable not list
        # (what is the difference? iterables don't support indexing?)
        current_list = list(zip(book_list, category_list, style_list))

        return render_template("home.html",
                               current=current_list,
                               search_form=search_form,
                               theme=user_theme)

    # if more than 3 books, display first book from ea category
    else:

        current_books = []
        i = 1

        # TODO: Refactor while loop to be more elegant/efficient. Perhaps use
        # next()? Or define a helper function?
        while len(current_books) < 3:

            for book in book_list:

                if book.category == i:

                    earlier_bk_in_cat = False

                    for tome in current_books:

                        if tome.category == i:

                            earlier_bk_in_cat = True
                            break

                    if earlier_bk_in_cat == False:

                        current_books.append(book)
                        break

            i += 1

        category_list = []
        [
            category_list.append(
                Category.query.filter_by(id=book.category).first())
            for book in current_books
        ]

        style_list = []
        # TODO: loop through categories and add style starting with blue, green, yellow,
        # then red, purple, and orange. Do this by index in list, not name value
        for category in category_list:

            style_list.append(cat_styles[category.name])

        current_list = list(zip(current_books, category_list, style_list))

        # if booklist < 6, add all over 3 to upcoming
        upcoming_books = []
        if len(book_list) <= 6:
            for book in book_list:
                if book not in current_books:
                    upcoming_books.append(book)

            category_list = []
            [
                category_list.append(
                    Category.query.filter_by(id=book.category).first())
                for book in upcoming_books
            ]

            style_list = []
            for category in category_list:

                style_list.append(cat_styles[category.name])

            upcoming_list = list(zip(upcoming_books, category_list,
                                     style_list))

        # else add 4, 5, 6 to upcoming
        else:

            i = 1
            while len(upcoming_books) < 3:
                for book in book_list:
                    if book not in current_books:

                        if book.category == i:

                            earlier_bk_in_cat = False

                            for tome in upcoming_books:

                                if tome.category == i:
                                    earlier_bk_in_cat = True
                                    break

                            if earlier_bk_in_cat == False:
                                upcoming_books.append(book)
                                break

                i += 1

            category_list = []
            [
                category_list.append(
                    Category.query.filter_by(id=book.category).first())
                for book in upcoming_books
            ]

            style_list = []
            for category in category_list:

                style_list.append(cat_styles[category.name])

            upcoming_list = list(zip(upcoming_books, category_list,
                                     style_list))

        return render_template("home.html",
                               current=current_list,
                               upcoming=upcoming_list,
                               search_form=search_form,
                               theme=user_theme)
Example #39
0
def edit_list():

    # form for search in navbar (since this is the same for all routes,
    # except login and register, this should probably be set in the app.py
    # file with other configuration stuff)
    search_form = SearchForm()

    # get user
    email = session["user"]
    user = User.query.filter_by(email=email).first()
    user_theme = "dark-theme"

    book_list = Book.query.filter_by(user=user.id, read=False).all()
    category_list = []

    [
        category_list.append(
            Category.query.filter_by(id=book.category).first())
        for book in book_list
    ]

    book_category_list = list(zip(book_list, category_list))

    form = AddBookForm()

    if request.method == "GET":

        if request.args:
            book = Book.query.filter_by(id=request.args.get("book_id")).first()
            book.category = int(request.args.get("category_id"))

            db.session.commit()

            return redirect(url_for("edit_list"))

        return render_template("edit-list.html",
                               form=form,
                               search_form=search_form,
                               list=book_category_list,
                               theme=user_theme)

    if form.validate_on_submit():

        # get form data
        title = form.title.data
        author = form.author.data
        category = form.category.data
        user = user.id
        date_added = datetime.utcnow()
        read = False
        rating = None
        review = None
        isbn = form.isbn.data

        book = Book(title, author, category, user, date_added, read, rating,
                    review, isbn)

        db.session.add(book)
        db.session.commit()

        flash(f"{title} added to reading list!")

        return redirect(url_for("edit_list"))

    for error in form.errors.items():

        flash(f"{error[1][0]}!", "error")

    return render_template("edit-list.html",
                           form=form,
                           search_form=search_form,
                           list=book_category_list,
                           theme=user_theme)
Example #40
0
def before_request():
    if current_user.is_authenticated:
        current_user.last_seen = datetime.utcnow()
        db.session.commit()
        g.search_form = SearchForm()
Example #41
0
File: view.py Project: jorluft/fla
    def show(self, action):
        """ Render respective templates for search [search page, search results page etc]"""
        try:
            data = {}
            if action == "" or action == "results":  #this is the search page
                SC = SearchController()
                if request.args.get("get") == "search-history":
                    search_history = []
                    for item in SC.get_search_history():
                        search_history.append({
                            "title":
                            item["title"],
                            "search_id":
                            str(item["_id"]),
                            "created_on":
                            str(item["created_on"]),
                            "details":
                            item["searchparams"]
                        })
                    return self.json_out(search_history)

                search_template = "search"
                searchform = SC.prepare_form_data(SearchForm(request.form))
                if action == "results":
                    searchparams = None
                    savesearchform = SaveSearchForm(request.form)
                    search_template = "results"
                    if request.form:
                        if "searchparams" in request.form:
                            if savesearchform.validate():
                                try:
                                    searchparams = ast.literal_eval(
                                        savesearchform.data["searchparams"])
                                    if type(searchparams) == dict:
                                        return self.json_out(
                                            SC.save_search(
                                                searchparams,
                                                title=savesearchform.title.data
                                            ))
                                except Exception as e:
                                    return self.json_out({
                                        "status":
                                        "failed",
                                        "message":
                                        "Incorrect search parameters received."
                                    })
                            else:
                                return self.json_out({
                                    "status":
                                    "failed",
                                    "message":
                                    self.get_wtf_errors(savesearchform.errors)
                                })
                        else:
                            if searchform.validate():
                                searchparams = searchform.data
                            else:
                                search_template = "search"

                    elif request.args.get("search_id"):
                        searchparams = SC.get_search_params(
                            search_id=request.args.get("search_id"))
                    else:
                        return redirect(url_for("search.index", action=""))

                    savesearchform.searchparams.data = searchparams
                    data.update(
                        {"media_items": SC.get_search_results(searchparams)})
                    data.update({"savesearchform": savesearchform})

                elif request.args.get("delete"):
                    return self.json_out(
                        SC.delete_search_history(
                            search_id=request.args.get("delete")))

                data.update({"searchform": searchform})
            return self.render("search/" + search_template + ".html",
                               data=data)
        except Exception as e:
            self.error_handle.get_error(
                error=str(e), occurred_at="mad.modules.SearchView.show()")
            abort(500)
Example #42
0
 def get_context_data(self, **kwargs):
     self.form = SearchForm(self.get_app_models(self.request.user.username))
     return {'form': self.form}
Example #43
0
def before_request():
    g.search_form = SearchForm()
Example #44
0
def search_results():

    search_form = SearchForm()
    add_book_form = AddBookForm()
    search_type = search_form.search_type.data
    search_term = search_form.search_term.data
    query = search_type + "+" + search_term
    user_theme = "dark-theme"

    # access credentials file to get API_KEY
    with open("credentials.json") as creds:
        secrets = json.load(creds)

    # create service object to build requests
    service = build('books',
                    'v1',
                    developerKey=secrets["credentials"]["API_KEY"])

    # Create request object. Returns an apiclient.http.HttpRequest object that
    # encapsulates all information needed to make the request, but it does not
    # call the API.
    request = service.volumes().list(source="public", q=query)

    # Execute request. It returns a Python object built from the JSON response.
    # You can print this object or refer to the Books API documentation to
    # determine its structure.
    response = request.execute()

    # Create results object to pass into render_template
    results = []

    for book in response.get('items', []):

        # null checks for fields used

        try:
            title = book["volumeInfo"]["title"]

        except KeyError as e:

            title = "No title found."
            print(e)

        try:

            authors = book["volumeInfo"]["authors"]
            num_authors = len(book["volumeInfo"]["authors"])

        except KeyError as e:

            authors = "No authors listed."
            num_authors = 0
            print(e)

        try:
            industry_identifiers = book["volumeInfo"]["industryIdentifiers"]

            isbn_13 = industry_identifiers[0].get("identifier")

        except KeyError as e:
            isbn_13 = "No ISBN-13 available."
            print(e)

        results.append({
            "title": title,
            "authors": authors,
            "num_authors": num_authors,
            "isbn_13": isbn_13
        })

    return render_template("search-results.html",
                           search_form=search_form,
                           add_book_form=add_book_form,
                           results=results,
                           theme=user_theme)
Example #45
0
def home():
	form = SearchForm()
	if form.validate_on_submit():
		redirect_url = url_for('text', book=form.book.data, seed=form.seed.data)
		return redirect(redirect_url)
	return render_template('search.html', form=form)
Example #46
0
def chart_js():
    searchForm = SearchForm()
    return render_template("charts-chartjs.html", searchForm=searchForm)
Example #47
0
def result():
    form = SearchForm()
    if request.method == 'POST':

        item = form.item.data
        model = form.model.data
        color = form.color.data
        search_list = list(filter(None, [item, model, color]))
        searchString = ','.join(search_list).replace(',', ' ')

        #dbConn = pymongo.MongoClient("mongodb://localhost:27017/")  # opening a connection to Mongo for local host
        # or
        #dbConn = pymongo.MongoClient() # openning a connection to Mongo client when deploying in cloud/heroku
        #also Mongo needs to be installed in the venv and requirement.txt will have to list mongo
        #db = dbConn['crawlerDB']
        #reviews = db[searchString].find({})
        #if reviews.count() > 0:
        #    return render_template('results.html', reviews=reviews)

        #else:
        #rating_list = []
        #review_list = []
        #user_list = []
        #product = []
        reviews = []
        #SearchResult = []

        #table = db[searchString]
        search_len = len(search_list)
        if search_len == 1:
            temp_url = search_list[0]
        elif search_len == 2:
            temp_url = search_list[0] + '%20' + search_list[1]
        else:
            temp_url = search_list[0] + '%20' + search_list[
                1] + '%20' + search_list[2]

        baseurl = 'https://www.flipkart.com'
        landing_page_url = baseurl + '/search?q=' + temp_url
        landing_data = requests.get(landing_page_url)

        if landing_data.status_code == requests.codes.ok:
            landing_soup = BeautifulSoup(landing_data.content, 'html.parser')
            if landing_soup.findAll("div", {"class": "DUFPUZ"}):
                return 'Please check the spelling or search something else.'

            else:

                bigboxes = landing_soup.findAll("div",
                                                {"class": "bhgxx2 col-12-12"})
                for div in bigboxes:
                    temp = div.a['href']
                    # print('temp: {}'.format(temp))
                    # print('z'*100)
                    if 'marketplace' in temp:
                        # print('final temp: {}'.format(temp))
                        break
                    else:
                        continue
                prod_page_url = baseurl + temp
                review_req = requests.get(prod_page_url)
                review_soup = BeautifulSoup(review_req.content, 'html.parser')

                if review_soup.find('div', {'class': 'swINJg'}):
                    all_reviews_link = review_soup.find(
                        'div', {'class': 'swINJg'})
                    review_data = str(
                        all_reviews_link.find_parent().get('href'))
                    review_url = baseurl + review_data
                    searchResult = review_soup.find('div', {
                        'class': '_29OxBi'
                    }).get_text()
                    for i in range(1, 3):
                        final_url = review_url + '&page=' + str(1)
                        final_req_data = requests.get(final_url)
                        review_page = BeautifulSoup(final_req_data.content,
                                                    'html.parser')
                        all_reviews = review_page.find_all(
                            'div', {'class': '_3gijNv col-12-12'})
                        x = len(all_reviews)
                        if x > 10:
                            only_review = all_reviews[-11:x - 1]

                        else:
                            only_review = all_reviews[2:x - 1]

                        for reviewbox in only_review:

                            rating = reviewbox.get_text()[0]
                            #rating_list.append(rating)

                            if reviewbox.find_all('p',
                                                  {'class': '_3LYOAd'}) == []:
                                user_names = 'No Name given'
                            else:
                                user_names = reviewbox.find_all(
                                    'p', {'class': '_3LYOAd'})[0].text
                            reviewer_names = user_names
                            #reviewer_names = reviewbox.find_all('p', {'class': '_3LYOAd'})[0].text
                            #user_list.append(reviewer_names)

                            all_reviews_img = reviewbox.img
                            next_tag = all_reviews_img.next_element
                            review = next_tag.text
                            #review_list.append(review)
                            #product.append(searchString)
                            #SearchResult.append(searchResult)

                            mydict = {
                                "Product_you_Searched": searchString,
                                "Search_Result": searchResult,
                                "Rating": rating,
                                "Review": review,
                                "User_Name": reviewer_names
                            }
                            #                    x = table.insert_one(mydict)
                            reviews.append(mydict)

            #           review_dict = {
            #                'searchResult': np.array(SearchResult).ravel(),
            #                'Product_you_Searched': np.array(product).ravel(),
            #                'Rating': np.array(rating_list).ravel(),
            #                'Review': np.array(review_list).ravel(),
            #                'User_Name': np.array(user_list).ravel()

            #                          }
            #            filename = searchString + ".csv"
            #            review_df = pd.DataFrame(review_dict)
            #            review_df.to_csv(filename)
                    return render_template('results.html', reviews=reviews)

                else:
                    return 'reviews of ' + searchString + ' is not available.'
            #else:
            #    return 'Please check the spelling or search something else.'
    else:
        return render_template('search.html', form=form)
Example #48
0
def index():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('search') + '?term={}'.format(form.data['search_term']))
    return render_template('index.html', form=form)
Example #49
0
def index():
    form = SearchForm()
    if form.validate_on_submit():
        return redirect(url_for('search', query=form.search.data))
    return render_template('index.html', posts=allPosts(), form=form)
Example #50
0
def index():
    """
    Displays main page.
    """
    form = SearchForm()
    return render_template('main_page.html', form=form)
Example #51
0
def index():
    if request.method == 'POST':
        print("我接到了post请求")
        form = SearchForm()
        if form.validate_on_submit():
            keyword = form.keyword.data
        else:
            abort(404)
        print("keyword = ", keyword)
        if is_string_validate(keyword):
            print("输入有误,请确认后重新输入")
            messages = "输入有误,请确认后重新输入"
            search_data = ""
            seo = {
                "title": "搜索结果页面",
                "keywords": "首页关键词",
                "description": "首页描述"
            }
            return render_template("search.html",
                                   seo=seo,
                                   books_cates=BOOK_CATES,
                                   form=SearchForm(),
                                   messages=messages,
                                   search_data=search_data)
        book = Book()
        search_data = book.search_infos_by_key(keyword)
        if len(search_data) == 0:
            print("没有获得结果")
            messages = ""
            search_data = ""
            seo = {
                "title": "搜索结果页面",
                "keywords": "首页关键词",
                "description": "首页描述"
            }
            return render_template("search.html",
                                   seo=seo,
                                   books_cates=BOOK_CATES,
                                   form=SearchForm(),
                                   messages=messages,
                                   search_data=search_data)
        else:
            print("有获得结果")
            messages = ""
            seo = {
                "title": "搜索结果页面",
                "keywords": "首页关键词",
                "description": "首页描述"
            }
            return render_template("search.html",
                                   seo=seo,
                                   books_cates=BOOK_CATES,
                                   form=SearchForm(),
                                   messages=messages,
                                   search_data=search_data)
    book = Book()
    xuanhuan_data = book.get_xuanhuan_top5()
    xiuzhen_data = book.get_xiuzhen_top5()
    dushi_data = book.get_dushi_top5()
    lishi_data = book.get_lishi_top5()
    wangyou_data = book.get_wangyou_top5()
    kehuan_data = book.get_kehuan_top5()
    yanqing_data = book.get_yanqing_top5()
    quanben_data = book.get_quanben_top5()
    # print("用这个去区分每个不同的域名给他不同的关键词和描述 ------------------------>", request.path)
    seo = {
        "title": TITLES[request.path][0],
        "keywords": TITLES[request.path][1],
        "description": TITLES[request.path][2]
    }
    return render_template("index.html",
                           seo=seo,
                           books_cates=BOOK_CATES,
                           form=SearchForm(),
                           xuanhuan_data=xuanhuan_data,
                           xiuzhen_data=xiuzhen_data,
                           dushi_data=dushi_data,
                           lishi_data=lishi_data,
                           wangyou_data=wangyou_data,
                           kehuan_data=kehuan_data,
                           yanqing_data=yanqing_data,
                           quanben_data=quanben_data)
Example #52
0
def inject():
    return dict(search_form=SearchForm())
Example #53
0
def search_campaigns(offset):
    cursor = get_cursor()
    form = SearchForm()
    pages = None

    if form.validate_on_submit():
        current_app.logger.info("searching")
        query = " & ".join(form.search.data.split(' '))
        current_app.logger.info("query: " + query)
        cursor.execute(
            """
            SELECT c.name, c.description, c.image, c.id AS campaign_id, get_total_donations(c.id) AS amount_donated, 
            c.amount_requested, ceil((get_total_donations(c.id)/c.amount_requested)*100) AS percentage
            FROM campaign c
            INNER JOIN campaign_relation cr ON c.id = cr.campaign_id
            INNER JOIN user_account ua ON cr.user_account_id = ua.id
            INNER JOIN user_profile up ON ua.id = up.user_account_id where cr.user_role='owner'
            AND to_tsvector('english', 
            coalesce(c.description, '') || ' ' ||  
            coalesce(c.name, '') || ' ' || 
            coalesce(up.first_name, '') || ' ' || 
            coalesce(up.last_name, ''))
            @@ to_tsquery('english', %s) ORDER BY ts_rank_cd(
            to_tsvector('english', 
            coalesce(c.description, '') || ' ' || 
            coalesce(c.name, '') || ' ' || 
            coalesce(up.first_name, '') || ' ' || 
            coalesce(up.last_name, '')),
            to_tsquery('english', %s)) DESC;
        """, (
                query,
                query,
            ))
        campaigns = cursor.fetchall()
        current_app.logger.info(str(campaigns))

        return render_template("campaign/gallery.html",
                               search_term=form.search.data,
                               campaigns=campaigns,
                               form=form)

    cursor.execute("""
        SELECT COUNT(*) FROM campaign;
    """)
    pages = math.ceil(cursor.fetchone()[0] / 9)

    cursor.execute(
        """
        SELECT c.id AS campaign_id, c.name, c.description, c.image, c.amount_requested, c.date_created,                           
        c.last_modified, up.id AS owner_id, up.first_name, up.last_name, up.profile_image, 
        up.description AS owner_description, get_total_donations(c.id) AS amount_donated, 
        ceil((get_total_donations(c.id)/c.amount_requested)*100) AS percentage  
        FROM campaign c                                                                                                           
        INNER JOIN campaign_relation cr on c.id = cr.campaign_id                                                                
        INNER JOIN user_account ua on cr.user_account_id = ua.id                                                                
        INNER JOIN user_profile up on ua.id = up.user_account_id WHERE cr.user_role='owner' 
        ORDER BY c.date_created ASC OFFSET %s ROWS LIMIT 9;
        """, (offset * 9, ))

    campaigns = cursor.fetchall()
    return render_template("campaign/gallery.html",
                           search_term=None,
                           campaigns=campaigns,
                           form=form,
                           pages=pages)
Example #54
0
def links(language):
    '''
    Allow a user to view and search links for a language.
    Credit: Text search
    https://stackoverflow.com/questions/48371016/pymongo-how-to-use-full-text-search
    https://stackoverflow.com/questions/50071593/pymongo-language-override-\
        unsupported-c-when-creating-index
    '''
    links = list(
        mongo.db.links.find({
            "language": language
        }).sort([("topic", 1), ("link_type", 1), ("link_name", 1)]))
    group_topics = mongo.db.links.aggregate([{
        "$match": {
            "language": language
        }
    }, {
        "$group": {
            "_id": "$topic"
        }
    }, {
        "$sort": {
            "_id": 1
        }
    }])
    form = SearchForm()
    if form.validate_on_submit():
        mongo.db.links.create_index([("$**", "text")], language_override="en")
        links_search = list(
            mongo.db.links.find({
                "language": language,
                "$text": {
                    "$search": form.tsearch.data
                }
            }).sort([("topic", 1), ("link_type", 1), ("link_name", 1)]))
        if links_search == []:
            flash(f'Sorry no results for {form.tsearch.data}', 'search')
        else:
            links = links_search
            group_topics = mongo.db.links.aggregate([{
                "$match": {
                    "language": language,
                    "$text": {
                        "$search": form.tsearch.data
                    }
                }
            }, {
                "$group": {
                    "_id": "$topic"
                }
            }, {
                "$sort": {
                    "_id": 1
                }
            }])
            flash(f'Links filtered by {form.tsearch.data}', 'search')
    group_topics = list(group_topics)
    return render_template("links.html",
                           links=links,
                           group_topics=group_topics,
                           language=language,
                           form=form,
                           sample1=session["sample1"],
                           sample2=session["sample2"],
                           sample3=session["sample3"],
                           sample4=session["sample4"],
                           quote=session["quote"])
Example #55
0
def dashboard():
    '''
    Page dashboard.
    Protected area. Only accessible with login.
    '''
    form = SearchForm()
    results = False
    # Search
    if request.method == 'POST':
        # Add Wallaviso
        if 'add' in request.form:
            searchs = Search.query.filter_by(
                user_id=session['user']['id']).all()
            searchs_len = len(searchs)
            if searchs_len < session['user']['limit_notifys']:
                # Search
                my_search = Search()
                my_search.name = request.form['name']
                my_search.lat = request.form['lat']
                my_search.lng = request.form['lng']
                my_search.distance = request.form['distance']
                my_search.max_price = request.form['max_price']
                my_search.min_price = request.form['min_price']
                if form.max_price.data == '':
                    my_search.max_price = 0
                if form.min_price.data == '':
                    my_search.min_price = 0
                my_search.user_id = session['user']['id']
                db.session.add(my_search)
                db.session.flush()
                try:
                    db.session.commit()
                    flash(
                        f"¡Wallaviso activado! Ya puedes añadir el siguiente enlace en tu lector de RSS: http://www.wallaviso.com{ url_for('rss_view', id=my_search.id) }",
                        'success')
                except BaseException:
                    db.session.rollback()
                    flash(
                        '¡Ups! Algo ha pasado. ¿Puedes volver a intentarlo?.',
                        'danger')

                results = False
                form.name.data = ''
                return redirect(url_for('dashboard'))
            else:
                if session['user']['rol_id'] == 1:
                    flash(
                        'No puedes tener más de {limit} Wallavisos. ¿Por qué no pasas a cuenta Premium  con {premium} Wallaviso?'
                        .format(limit=LIMIT_SEARCH,
                                premium=LIMIT_SEARCH_PREMIUM), 'danger')
                else:
                    flash(
                        'No puedes tener más de {limit} Wallavisos. ¿Por qué no borras alguno?'
                        .format(limit=LIMIT_SEARCH), 'danger')

        # Remove
        elif 'delete' in request.form:
            my_search = Search.query.filter_by(
                id=request.form['delete'],
                user_id=session['user']['id']).first()
            db.session.delete(my_search)
            try:
                db.session.commit()
                flash('¡Wallaviso borrado!', 'success')
            except BaseException:
                db.session.rollback()
                flash('¡Ups! Algo ha pasado. ¿Puedes volver a intentarlo?.',
                      'danger')
    searchs = Search.query.filter_by(user_id=session['user']['id']).all()
    searchs_len = len(searchs)
    # Search Limit
    limit_searchs = LIMIT_SEARCH
    if session['user']['rol_id'] > 1:
        limit_searchs = LIMIT_SEARCH_PREMIUM

    return render_template('web/dashboard/searchs.html',
                           form=form,
                           searchs=searchs,
                           searchs_len=searchs_len,
                           searchs_res=searchs_len -
                           session['user']['limit_notifys'],
                           results=results,
                           LIMIT_RESULTS=LIMIT_RESULTS,
                           LIMIT_SEARCHS=limit_searchs,
                           URL_API_POSTAL_CODE=URL_API_POSTAL_CODE,
                           DEBUG=app.config['DEBUG'])
Example #56
0
def notes(language):
    '''
    Allow logged in user view and search their own notes for a language.
    Credit: Text search
    https://stackoverflow.com/questions/48371016/pymongo-how-to-use-full-text-search
    https://stackoverflow.com/questions/50071593/pymongo-language-override-\
        unsupported-c-when-creating-index
    '''
    notes = list(
        mongo.db.notes.find({
            "language": language,
            "user_id": ObjectId(current_user.id)
        }).sort([("topic", 1), ("note_name", 1)]))
    if notes == []:
        flash(f'Click Add New + to add your first {language} note.', 'first')
    group_topics = mongo.db.notes.aggregate([{
        "$match": {
            "language": language,
            "user_id": ObjectId(current_user.id)
        }
    }, {
        "$group": {
            "_id": "$topic"
        }
    }, {
        "$sort": {
            "_id": 1
        }
    }])
    form = SearchForm()
    if form.validate_on_submit():
        mongo.db.notes.create_index([("$**", "text")], language_override="en")
        notes_search = list(
            mongo.db.notes.find({
                "language": language,
                "user_id": ObjectId(current_user.id),
                "$text": {
                    "$search": form.tsearch.data
                }
            }).sort([("topic", 1), ("note_name", 1)]))
        if notes_search == []:
            flash(f'Sorry no results for {form.tsearch.data}', 'search')
        else:
            notes = notes_search
            group_topics = mongo.db.notes.aggregate([{
                "$match": {
                    "language": language,
                    "user_id": ObjectId(current_user.id),
                    "$text": {
                        "$search": form.tsearch.data
                    }
                }
            }, {
                "$group": {
                    "_id": "$topic"
                }
            }, {
                "$sort": {
                    "_id": 1
                }
            }])
            flash(f'Notes filtered by {form.tsearch.data}', 'search')
    group_topics = list(group_topics)
    return render_template("notes.html",
                           notes=notes,
                           group_topics=group_topics,
                           language=language,
                           form=form,
                           sample1=session["sample1"],
                           sample2=session["sample2"],
                           sample3=session["sample3"],
                           sample4=session["sample4"],
                           quote=session["quote"])
Example #57
0
def search(type_tag):
    form = SearchForm()
    type_tag = int(type_tag)
    call_tag = api_params.get('call_tags').get(type_tag)
    tag = call_tag.capitalize()

    if form.validate_on_submit():
        api_request = generate_api_call(call_tag)  # w/o anything else
        #w/o considering it might be a list
        park_code = ""
        state_code = ""
        start = 0
        q = ""
        fields = []
        sort = []
        limit = 50
        #checks if our form is receiving any data
        if form.parkCode.data != None:
            park_code = form.parkCode.data
        if form.stateCode.data != None:
            state_code = form.stateCode.data
        if form.start.data != None:
            start = form.start.data
        if form.q.data != None:
            q = form.q.data
        if form.limit.data != None:
            limit = form.limit.data
        if form.fields.data != None:
            field_string = form.fields.data
            fields = field_string.split(",")
        if form.sort.data != None:
            sort_string = form.sort.data
            sort = sort_string.split(",")
        #official api call
        api_request = generate_api_call(call_tag,
                                        park_code=park_code,
                                        state_code=state_code,
                                        start=start,
                                        q=q,
                                        fields=fields,
                                        sort=sort,
                                        limit=limit)
        #checks if api call is right
        print(api_request)
        #makes call + get data
        r = requests.get(api_request)
        num = int(json.loads(r.text)['total'])
        print("num: " + str(num))
        data = json.loads(r.text)['data']
        limit = min(num, limit)
        #distinction in searches
        if type_tag == 1:
            #TODO alerts
            return render_template('alerts.html',
                                   title='Alerts',
                                   park_name="",
                                   alerts=data,
                                   num_alerts=limit)
        elif type_tag == 2:
            #TODO articles
            return render_template('articles.html',
                                   title='Articles',
                                   articles=data,
                                   num_articles=limit)
        elif type_tag == 3:
            #TODO campgrounds
            return render_template('campgrounds.html',
                                   title='Campgrounds',
                                   campgrounds=data,
                                   num_campgrounds=limit,
                                   park_code=park_code,
                                   abb_to_full=states,
                                   state_code=state_code)
        elif type_tag == 4:
            #TODO events
            return render_template('events.html',
                                   title='Events',
                                   events=data,
                                   num_events=limit,
                                   park_code=park_code,
                                   abb_to_full=states,
                                   state_code=state_code)
        elif type_tag == 5:
            #TODO lessonplans
            return render_template('lessons.html',
                                   title='Lesson Plans',
                                   lessons=data,
                                   num_lessons=limit,
                                   park_code=park_code,
                                   abb_to_full=states,
                                   state_code=state_code)
        elif type_tag == 6:
            #TODO newsreleases
            #do we need an initial page???
            return render_template('all_news.html',
                                   title='News',
                                   num_news=limit,
                                   total_news=num,
                                   news_all=data)
        elif type_tag == 7:
            state_abb = ""
            state_full = ""
            return render_template('parks.html',
                                   title='Parks',
                                   num_parks=num,
                                   list_of_parks=data,
                                   state_abb=state_abb,
                                   state_full=state_full,
                                   states=states)
        elif type_tag == 8:
            #TODO people
            return render_template('people.html',
                                   title='People',
                                   people=data,
                                   num_people=limit)
        elif type_tag == 9:
            #TODO places
            return render_template('places.html',
                                   title='Places',
                                   places=data,
                                   num_places=limit)
        else:
            #TODO visitorcenters
            latLong = []
            lat = 0
            lng = 0
            all_vc_map_queries = []
            for i in range(limit):
                map_query = None
                vc = data[i]
                if vc.get('latLong') != "":
                    latLong = re.findall('\-?\d+', vc.get('latLong'))
                    print("latLong: " + ",".join(latLong))
                    lat = str(Decimal(str(latLong[0]) + "." + str(latLong[1])))
                    print("lat: " + str(lat))
                    lng = str(Decimal(str(latLong[2]) + "." + str(latLong[3])))
                    print("long: " + str(lng))
                    # map_query = "https://www.google.com/maps/search/?api=1&query=" + str(lat) + "," + str(lng)
                    map_query = {"lat": lat, "lng": lng}
                all_vc_map_queries.append(map_query)
            return render_template('vcs.html',
                                   title='Visitor Centres',
                                   vcs=data,
                                   num_vc=limit,
                                   vc_map_queries=all_vc_map_queries)

    return render_template('search.html',
                           title="Search Form",
                           form=form,
                           search_type=tag)
Example #58
0
def aresponse(request, id=None, keywords=None, page=None, msg=None):
    c = RequestContext(request)

    from forms import SearchForm
    sform = SearchForm()

    if request.method == 'GET':
        if id:
            apk = apks.objects.get(version=id, nombre=keywords)

            rel = apk.relativo.split(":")
            if len(rel) > 0:
                del rel[0]
            import os
            dir = os.path.dirname(apk.ruta)

            return render_to_response("desc.html", {
                "dir": dir,
                "rel": rel,
                "apk": apk,
                "err": False,
                "sform": sform
            },
                                      context_instance=c)
        elif keywords != None and page != None:
            asearch = keywords
            searchp = asearch.split()

            if len(searchp) == 0:
                return render_to_response("main.html", {
                    "err": False,
                    "sform": sform
                },
                                          context_instance=c)

            if keywords == "*all*":
                apk = apks.objects.order_by("nombre")
            else:
                apk = search_keywords(apks, searchp)

            paginator = Paginator(apk, 20)
            try:
                lapk = paginator.page(page)
            except PageNotAnInteger:
                lapk = paginator.page(1)
            except EmptyPage:
                lapk = paginator.page(paginator.num_pages)

            if len(apk) > 0:
                return render_to_response("main.html", {
                    "err": False,
                    "cursor": lapk,
                    "asearch": asearch,
                    "sform": sform
                },
                                          context_instance=c)
            else:
                return render_to_response("main.html", {
                    "err": True,
                    "msg": "No se han encontrado coincidencias",
                    "sform": sform
                },
                                          context_instance=c)

        elif msg != None:
            return render_to_response("main.html", {
                "err": True,
                "msg": msg,
                "sform": sform
            },
                                      context_instance=c)
        else:
            return render_to_response("index.html", {
                "err": False,
                "cursor": [],
                "sform": sform
            },
                                      context_instance=c)
    else:
        pass
Example #59
0
def before_request():
    g.user = current_user
    g.search_form = SearchForm()
Example #60
0
def search():
    form = SearchForm(request.form)
    if form.is_submitted():
        term = form.term.data
        return redirect(url_for('results', term=term))
    return render_template('home.html', form=form)