def index(key_query=None, filter_query=None, filter_form=None):
    # If we don't have a get query or saved sort key, default to sorting by lname
    if key_query is None:
        if bottle.request.query.key_query:
            key_query = bottle.request.query.key_query
        elif 'key_query' in bottle.request.session:
            key_query = bottle.request.session['key_query']
        else:
            key_query = 'lname'

    # Save key_query so that we get consistent results across refreshes
    bottle.request.session['key_query'] = key_query

    # Grab a sort function to pass to sorted()
    sort_key = sort_keys[key_query]

    if filter_form is None:
        filter_form = ContactForm()
        filter_func = lambda x: True
    else:
        filter_func = functools.partial(contact_filter, filter_form.data)

    # Refresh contacts and filter by any user-entered conditions
    contacts = refresh_contact_dict()
    filtered_contacts = filter(filter_func, contacts)

    # Grab contacts and place in dictionary for sorting
    if contacts:
        sorted_contacts = sorted(filtered_contacts, key=sort_key)
        return bottle.template('templates/base',
                               search_form=ContactSearchForm(),
                               filter_form=filter_form, contacts=sorted_contacts)

    else:
        return bottle.template('templates/base')
Example #2
0
def do_registrar():
    """
    """
    _auth = Auth()
    if not _auth.is_login:
        errors = [] #errores 
        #validacion de campos vacios
        _username = request.forms.get('username')
        if _username == "":
            errors.append("El campo Usuario esta vacio")

        #validacion de contrasenias
        _password = request.forms.get('password')
        repassword = request.forms.get('repassword')
        if len(_password) < 8 or len(_password) >= 16:
            errors.append("la contrasenia debe tener entre 8 y 16 caracteres")
        if _password != repassword:
            errors.append("Las contrasenias no coinciden")

        _name = request.forms.get('name')
        if _name == "":
            errors.append("El campo Nombre esta vacio")
        
        _email = request.forms.get('email')
        if _email == "":
            errors.append("El campo Email esta vacio")

        if len(errors) == 0:
            #validacion de que no exista el usuario
            query = db.GqlQuery("SELECT * FROM User WHERE username = :1", _username)        
            if query.count() != 0:
                errors.append("El nombre de usuarios \"%s\" ya existe" %_username)
                form_error = True

            else:            
                user = User(
                    username = _username,
                    password = _password,
                    name = _name,
                    email = _email,
                )
                user.put()
                return template("auth/registrar-ok.html")

        else:
            form_error = True
        #si llego hasta aqui hay algun tipo de errors        
        data = {
            "errors" : errors,
            "form_error": form_error,
            "username": _username,
            "name": _name,
            "email": _email,
        }
        return template("auth/registrar.html", data)

    else:
        message = "Error ya has iniciado Session con la cuenta \"%s\" " %_auth.is_login()
        message += "en caso de querer proceder por fabor cierra la session actual."
        return template("message.html", {'message': message} )
Example #3
0
def send_mail():
    email = bottle.request.forms.get("email")
    scontent = bottle.request.forms.get("scontent")
    subject = bottle.request.forms.get("subject")
    if email == "":
        notification = "Please enter your e-mail address"
        return bottle.template("contact", dict(email="", subject="",scontent="",notification=notification,s="warning"))
    else:
        # To enable mailing, you shoudl go to the application Dashboard --> Administration --> Permissions
        # Add [email protected] and check your mailbox to verify the account.
        message = mail.EmailMessage(sender="JournalS Support <*****@*****.**>", #[email protected] is verified by google app engine, so it should be real
                            subject="Your message has been received")

        message.to = email
        message.bcc = "*****@*****.**" 
        message.body = """
        Dear Journal Seeker:

            Your message has been received.
            -------------------------------
        """
        message.body += scontent + "\n"
        message.body +="""
            -------------------------------
            We will contact you as soon as possible.
            Keep following and keep writing :)
        
        JournalS Team
        """
        message.send()
        notification = "Your message has been sent successfully."
        return bottle.template("contact", dict(email="", subject="",scontent="",notification=notification,s="success"))
Example #4
0
def search():
    subjects = ut.get_subjects()
    searchList = bottle.request.forms.getlist("subjects")
    if len(searchList) == 0:
         return bottle.template("home",subjects=subjects,keywordList=[],resultingList=[])
    keywordList = ",".join(searchList)   
    resultingList = ut.search_journals(searchList)
    return bottle.template("home",subjects=subjects,keywordList=keywordList,resultingList=resultingList)
Example #5
0
def listado():
    _auth = Auth()
    if _auth.is_login():
        data = {}
        user = db.GqlQuery("SELECT * FROM User WHERE username = :1", _auth.is_login()).fetch(1)[0]
        data['series'] = Serie.all().filter("user="******"series/listado.html", data)
    else:
        return template("sin-permisos.html")
Example #6
0
def login():
    """
        Iniciar Session
    """
    _auth = Auth()
    if not _auth.is_login():
        return template('auth/login.html')
    else:
        message = "Error ya has iniciado Session con la cuenta \"%s\" " %_auth.is_login()
        message += "en caso de querer proceder por fabor cierra la session actual."
        return template("message.html", {'message': message} )
Example #7
0
def getofferlist():
	bottle.debug(True)
	problemId = request.forms.get('problemid')
	logging.getLogger().setLevel(logging.DEBUG)
	logging.info(problemId)
	offers = dbfacade.getOffers(problemId)

	if not offers:
		mail.tempSendNewOffersNotification()
		return template("solutionpage_offers_table_empty")
	else:
		return template("solutionpage_offers_table", offers=offers)
Example #8
0
def logout():
    """
    Cerrar Session
    """
    response.delete_cookie("username", path="/")
    response.delete_cookie("is_admin", path="/")
    return template("auth/logout.html")
Example #9
0
def postaproblem():
	name = request.forms.get('name')
	city = request.forms.get('city')
	description = request.forms.get('description')
	email = request.forms.get('email')
	mail.sendConfirmationEmail(name, email) #TODO!!
	return template("postaproblem.tpl", email=email)
Example #10
0
def pads():
    #checks to see if any pad was updated via http form
    pad_one = request.query.get('item1')
    pad_two = request.query.get('item2')
    pad_three = request.query.get('item3')
    pad_four = request.query.get('item4')
    key_list = [pad_one, pad_two, pad_three, pad_four]

    #if any of the pads were updated
    if pad_one or pad_two or pad_three or pad_four:
        for index, pad in enumerate(key_list): #checks which pad was the one updated
            if pad:
                current_item = pad #the new item is saved in a variable
                number_pad = str(index+1) #the number of the pad is saved
                key = db.Key.from_path('Pad', number_pad)
                new = db.get(key) #fetches the database entity for the pad which was updated
                new.item = current_item #updates the item
                new.put()
                mail_send(number_pad, current_item) #sends email to the Pi
        if current_item not in [history.item for history in db.Query(History, projection=['item'])]: #checks if the item was never used before
            history_entry = History(item=current_item)
            history_entry.put() #add the item to history
        sleep(.25) #puts in a delay to give the website time to update the pads
        redirect('/pads') #redirects back to the base pads url to show changes
    history_list = [] #fetches all of the history entries
    for previous in db.Query(History, projection=['item']):
        history_list.append(previous.item)
    pad_dic = {} #fetches all of the pads data
    for pad in db.Query(Pad, projection=['item', 'number']):
        pad_dic[pad.number] = pad.item
    #displays the pad template with the history and pad data as input
    output = template('templates/pads', data=pad_dic, history_data=history_list)
    return output
Example #11
0
def listado():
    """
        Listado de Usuarios
        Nota: Requiere permiso administrado
    """
    users = db.GqlQuery("SELECT * FROM User")
    return template('auth/listado.html', {'users':users})
Example #12
0
def solutionpage():
	bottle.debug(True)
	#TODO:
	id = request.query.id
	if (dbfacade.problemIdIsLegit(id)):
		return template("solutionpage.tpl", ownername=dbfacade.getProblemOwnerName(id), ownerlocation=dbfacade.getProblemOwnerLocation(id), owneremail=dbfacade.getProblemOwnerEmail(id), problemdescription=dbfacade.getProblemDescription(id))
	else:
		return("<p>You entered an invalid problem ID!</p><p><a href=\"/\">To the front page</a></p>")
Example #13
0
def validateemail():
	#TODO:
	id = request.query.id
	if (id == "123456789"):
		mail.tempSendSolutionMail()
		return template("validate.tpl")
	else:
		redirect("/")
Example #14
0
def index():
    #pagina de inicio
    _auth = Auth() 
    if (_auth.is_login()):
        is_login = True
    else:
        is_login = False
    return template('home.html', {'is_login':is_login })
def signup_form(form=None):
    if form == None:
        form = SignupForm()

    return bottle.template('templates/base', {
        'target': "Sign up",
        'form': form,
        'action': 'signup',
    })
Example #16
0
def getofferdetails():
	bottle.debug(True)
	offerId = request.forms.get('offerid')
	#TODO: db (tietoja kyseisestä offerista)
	companyId = dbfacade.getCompanyId(offerId)
	companyName = dbfacade.getCompanyName(companyId)
	price = dbfacade.getOfferPrice(offerId)
	chat = dbfacade.getChatMessages(offerId)
	return template("solutionpage_modal_body", companyid=companyId, name=companyName, price=price, chat=chat)
Example #17
0
def weather():
   if request.query.lat != "" and request.query.lon != "":
      # Got what we need, make the template now.
      return template("templates/weather.tmpl", lat=request.query.lat, lon=request.query.lon)
   elif request.query.zipcode == None or request.query.zipcode == "":
      # Need zipcode
      return redirect('static/zip_form.html')
   else:
      # Need to get Lat Lon
      result = get_lat_lon(request.query.zipcode)
      redirect("/weather?lat="+result['lat']+"&lon="+result['lon'])
def add_form(form=None, upload_url=None):
    if form == None:
        form = ContactForm()

    if upload_url == None:
        upload_url = blobstore.create_upload_url("/add")

    return bottle.template('templates/base', {
        'target': "Add",
        'form': form,
        'action': upload_url,
    })
Example #19
0
def do_login():
    """
        Captura los datos de la vista para iniciar session
    """
    _auth = Auth()
    usr = request.forms.get('username')
    pwd = request.forms.get('password')

    if _auth.login(usr, pwd):
        redirect('/')
    else:
        return template('auth/login.html', {"login_error": True})
def login_form(form=None):
    # If the user is logged in, log out before rendering the log in form
    if 'user_key_str' in bottle.request.session:
        return logout_submit('/login')

    # Create a new form
    if form == None:
        form = LoginForm()

    return bottle.template('templates/base', {
        'target': "Login",
        'action': "/login",
        'form': form
    })
Example #21
0
def ProcessSearch():
    UPC = request.POST.get('Body')
    APIKEY = your_api_key               # Google Product Search API Key
    url = "https://www.googleapis.com/shopping/search/v1/public/products?key=%s&country=US&restrictBy=gtin:%s&rankBy=price:ascending" % (APIKEY, UPC)
    data = urllib.urlopen(url).read()
    d = json.loads(data)
    title = d["items"][0]["product"]["title"]
    price = d["items"][0]["product"]["inventories"][0]["price"]

    response.content_type = 'text/xml'

    values = {'title':title, 'price':price}

    return template('templates/twilio', data = values)
Example #22
0
def the_weather():
   results = get_weather(request.query.lat, request.query.lon)
   return template('templates/weather_data.tmpl'\
         , date=date_str() \
         , time=time_str() \
         , label0=results[0]["label"] \
         , label1=results[1]["label"] \
         , label2=results[2]["label"] \
         , temp0=results[0]["temp"] \
         , temp1=results[1]["temp"] \
         , temp2=results[2]["temp"] \
         , color0=results[0]["color"] \
         , color1=results[1]["color"] \
         , color2=results[2]["color"]);
def get_contact(key_str, form=None, upload_url=None):
    if form == None:
        # Retrieve contact data and create a form
        contact = ndb.Key(urlsafe=key_str).get()
        #bottle.request.session['contact'] = contact
        form = contact_to_form(contact)
    if upload_url == None:
        upload_url = blobstore.create_upload_url("/edit/" + key_str)

    return bottle.template('templates/base', {
        'target': "Edit",
        'form': form,
        'action': upload_url,
    })
Example #24
0
def root():
   car_data = ""
   names = request.query.names.split(',')
   dates = request.query.dates.split(',')
   terms = request.query.terms.split(',')
   miles = request.query.miles.split(',')
   bases = request.query.bases.split(',')


   for idx, name in enumerate(names):
      termYears = int(terms[idx]) / 12
      termMonths = int(terms[idx]) - int(termYears) * 12

      termYearsFloat = float(termYears) + float(termMonths)/12.0
      totalMiles = float(miles[idx]) * termYearsFloat

      # Date is in format YYYYMMDD
      startDate = datetime.strptime(dates[idx],"%Y%m%d")
      endYear = startDate.year + termYears
      endMonth = startDate.month + termMonths
      if endMonth > 12:
         endMonth = endMonth - 12
         endYear += 1

      endDate = datetime(endYear, endMonth, startDate.day)
      nowDate = datetime.now()

      nowDays = (nowDate - startDate).days
      totalDays = (endDate - startDate).days
      fract = float(nowDays) / float(totalDays)
      
      mileage = float(bases[idx]) + fract * totalMiles

      car_data += template('templates/car_row.tmpl', name=name, mileage=int(mileage), end_date=endDate.strftime("%Y/%m/%d"))
      #car_data += name + " " + dates[idx] + " " + terms[idx] + " " + miles[idx] + "</br>"

   return template('templates/main.tmpl',car_data=car_data)
Example #25
0
def do_registrar():
    _auth = Auth()
    if _auth.is_login():
        #field validation
        _name = request.forms.get('name')
        _day = request.forms.get('day')
        _url = request.forms.get('url')
        _chapter_url = request.forms.get('chapter_url')
        _num_chapters = request.forms.get('mun_chapters')
        _old_chapter = request.forms.get('old_chapter')

        #el usuario existe se supone que esta logueado sino cagada jaaj
        _user = db.GqlQuery("SELECT * FROM User WHERE username = :1", _auth.is_login()).fetch(1)[0]
        
        if _num_chapters <= _old_chapter:
            _old_chapter = _num_chapters
            _enabled = False
        else:
            _enabled = True

        serie = Serie(
            user = _user,
            name = _name,
            day = _day,
            url = _url,
            chapter_url = _chapter_url,
            num_chapters = int(_num_chapters),
            old_chapter = int(_old_chapter), #ultimo capitulo que salio    
            enabled = _enabled
        )
        serie.put()
       
        # Registro los capitulos
        n = int(_old_chapter) + 1
        for num in range(1, n):
            chapter = Chapter(
                serie = serie,
                number = num,
                url = serie.chapter_url %num,
                show = False
            )
            chapter.put()

        return "Serie Registrada"

        #return template("series/registrar.html")
    else:
        return template("sin-permisos.html")
Example #26
0
def grocery_list():
    to_delete = request.query.get('delete')
    #if the user removed something from the grocery list
    if to_delete:
        #delete the database entity and redirect back to the base url
        key = db.Key.from_path('Grocery', to_delete)
        db.delete(key)
        sleep(.25)
        redirect('/grocery_list')
    #requests all of the grocery list database entities
    groceries_list = []
    q = Grocery.all()
    for product in q.run():
        groceries_list.append(product.item)
    #displays the grocery list template with the current groceries as input
    output = template('templates/grocery_list', data=groceries_list)
    return output
Example #27
0
def index():
    return template('form.html')
Example #28
0
def do_index():
    data = {}
    data['name'] = request.forms.get('name')
    data['phone'] = request.forms.get('phone')
    return template('saludo.html', data)
Example #29
0
def DisplayForm():
    message = 'Hello World'
    output = bottle.template('templates/home', data = message)
    return output
Example #30
0
def index():
    return template('templates/home')
Example #31
0
def welcome():
    output = template('templates/welcome')
    return output
Example #32
0
def error404(code):
    return template('templates/404')
Example #33
0
def registrar():
    _auth = Auth()
    if _auth.is_login():
        return template("series/registrar.html")
    else:
        return template("sin-permisos.html")
Example #34
0
def process_search():
    search_query = request.GET.get('search_query', '').strip()
    query = search_query.lower()

    show_daverank = False
    results = False
    number_pages = 10
    number_videos = 5

    #Move this stuff to its own procedure tomorrow!
    if query.find('--') == 0:
        if query.find('--forum') == 0:
            redirect_url = 'http://www.udacity-forums.com/cs101/search/?q=' + urllib.quote(
                query[8:])
            return redirect(redirect_url)
        if query.find('--cs373') == 0:
            redirect_url = 'http://www.udacity-forums.com/cs373/search/?q=' + urllib.quote(
                query[8:])
            return redirect(redirect_url)
        if query.find('--python') == 0:
            redirect_url = 'http://docs.python.org/search.html?q=' + urllib.quote(
                query[9:])
            return redirect(redirect_url)
        if query.find('--searchwithpeterdotinfo') == 0:
            redirect_url = 'http://searchwithpeter.info/secretplans.html?q=' + urllib.quote(
                query[25:])
            return redirect(redirect_url)
        if query.find('--showmore') == 0:
            query = query[11:]
            search_query = query
            number_pages = 20
            number_videos = 10
        if query.find('--daverank') == 0:
            query = query[11:]
            search_query = query
            show_daverank = True

    if query.find('python') == 0:
        pyquery = query[7:]
    else:
        pyquery = query

    ddgurl_root = 'http://duckduckgo.com/?q=python+'
    ddgurl_suffix = urllib.quote(pyquery) + '&format=json'

    response = urllib.urlopen(ddgurl_root + ddgurl_suffix)
    response_json = response.read()

    pythonterm = json.loads(response_json)

    if pythonterm:
        pyterm_info = {}
        if pythonterm['AbstractSource'] == 'Python Documentation':
            pyterm = BeautifulSoup(pythonterm['AbstractText'])
            try:
                pyterm_code = pyterm.find('code').string
                pyterm.pre.decompose()
                pyterm_info['code'] = pyterm_code
            except:
                pyterm_info['code'] = None
            pyterm_desc = pyterm.get_text()
            pyterm_info['desc'] = pyterm_desc
            pyterm_info['url'] = pythonterm['AbstractURL']
            results = True
    else:
        pyterm_info = None

    query_words = query.split()
    for word in query_words:
        if word in stopwords:
            query_words.remove(word)

    query_urls = []
    for term in query_words:
        # Get all SearchTerm objects that match the search_query.
        q = SearchTerm.all().filter('term =', term).get()
        if q:
            query_urls.append(set(q.urls))

    if query_urls:
        query_url_set = set.intersection(*query_urls)
        query_url_list = list(query_url_set)

        if len(query_url_list) > 0:
            results = True
        if len(query_url_list) > 30:
            query_url_list = query_url_list[0:30]

        page_results = Page.all().filter(
            'url IN', query_url_list).order('-dave_rank').fetch(number_pages)
        page_dicts = []
        for page in page_results:
            page_info = {}
            query_index = page.text.find(query)
            if query_index != -1:
                i = page.text.find(' ', query_index - 25)
                excerpt_words = page.text[i:].split(' ')
                page_info['exact_match'] = True
            else:
                excerpt_words = page.text.split(' ')
                page_info['exact_match'] = False
            excerpt = ' '.join(excerpt_words[:50])

            page_info['text'] = excerpt
            page_info['title'] = page.title
            page_info['url'] = page.url
            page_info['daverank'] = page.dave_rank
            page_info['doc'] = page.doc
            page_dicts.append(page_info)
        page_dicts.sort(key=itemgetter('exact_match'), reverse=True)

        video_results = Video.all().filter(
            'url IN', query_url_list).order('-views').fetch(number_videos)
        video_dicts = []
        for video in video_results:
            video_info = {}
            subtitles = video.text.lower()
            query_index = subtitles.find(query)
            time_string = ''
            if query_index != -1:
                subtitle_list = subtitles.splitlines()
                for phrase in subtitle_list:
                    if phrase.find(query) != -1:
                        timestamp_index = subtitle_list.index(phrase) - 1
                        timestamp = subtitle_list[timestamp_index]
                        if len(timestamp) > 1:
                            minutes = timestamp[3:5]
                            seconds = timestamp[6:8]
                            time_string = '#t=' + minutes + 'm' + seconds + 's'
                            start = 60 * int(minutes) + int(seconds)
            if time_string:
                url = video.url + time_string
                video_info['exact_match'] = True
            else:
                url = video.url
                start = 0
                video_info['exact_match'] = False
            video_info['title'] = video.title
            video_info['url'] = url
            video_info['subtitle'] = video.text[-20:query_index:20]
            video_info['id'] = video.id
            video_info['start'] = start
            video_dicts.append(video_info)
        video_dicts.sort(key=itemgetter('exact_match'), reverse=True)

    else:
        page_dicts = None
        video_dicts = None

    query_string_words = query.split()

    return template('templates/results',
                    search_query=search_query,
                    query_string_words=query_string_words,
                    page_dicts=page_dicts,
                    video_dicts=video_dicts,
                    pyterm_info=pyterm_info,
                    show_daverank=show_daverank,
                    results=results)
Example #35
0
def search_form():
    output = template('templates/home')
    return output