Exemplo n.º 1
0
def js():
    bottle.response.content_type = 'application/javascript'
    
    lp = bottle.urljoin(bottle.request.url, bottle.url('/lp'))
    ct = bottle.urljoin(bottle.request.url, bottle.url('/ct'))
    
    return static.trackingjs % {'lp':lp, 'ct':ct}
Exemplo n.º 2
0
def js():
    bottle.response.content_type = 'application/javascript'

    lp = bottle.urljoin(bottle.request.url, bottle.url('/lp'))
    ct = bottle.urljoin(bottle.request.url, bottle.url('/ct'))

    return static.trackingjs % {'lp': lp, 'ct': ct}
Exemplo n.º 3
0
def delete():
    rut = request.forms.get('rut')
    opcion = ProfesorDelete(rut)
    if opcion == 1:  #exito
        redirect(url('/ProfesoresAll') + '#exitoborrar')
    if opcion == 2:  #error en ingreso
        redirect(url('/ProfesoresAll') + '#errorborrar')
Exemplo n.º 4
0
def address_delete(person_id):
    chosen_id = int(request.forms.chosen)
    addr = session.query(Address).filter_by(id=chosen_id).one()
    if addr.available:
        return redirect(url("address_list", person_id=person_id))
    session.delete(addr)
    session.commit()
    return redirect(url("address_list", person_id=person_id))
Exemplo n.º 5
0
Arquivo: app.py Projeto: vaultah/L
        def wrapper(*a, **kw):
            # Update the arguments with those we need in the function
            params = kw.copy()
            this = auth.Current(acid=request.cookies.get('acid'),   
                                token=request.cookies.get('token'))
            switch = request.query.get('switch')
            if switch is not None:
                _route_name = request['bottle.route'].name
                acct = Record(name=switch)
                if not acct.good():
                    if _route_name != 'sign_up':
                        redirect(url('sign_up', switch=switch))
                elif acct == this.record:
                    if _route_name != 'main':
                        redirect(url('main'))
                elif acct in this.records:
                    this.switch_to(acct)
                    if _route_name != 'main':
                        redirect(url('main'))
                else:
                    if _route_name != 'sign_in':
                        redirect(url('sign_in', switch=switch))

            if this.loggedin:
                # That's right, set the ACID cookie on every request
                response.set_cookie(name='acid', path='/', max_age=this.acid[1],
                                    value=this.acid[0],
                                    domain=request.environ.get('DOTTED_DOMAIN'))
                
                if this.set_token:
                    response.set_cookie(name='token', max_age=this.token[1], value=this.token[0],
                                        domain=request.environ.get('DOTTED_DOMAIN'), path='/')

            if this.loggedin:
                nots = {x.id: x.get_html(env.get_template('macros/notifications.html'))
                        for x in load_notifications(this.record)}
            else:
                nots = {}

            params.update(
                current=this,
                current_profile=profile.profile(this.record) if this.loggedin else {},
                notifications=nots,
                accounts=[x.add({'profile': profile.profile(x)}) for x in this.records],
                loggedin=this.loggedin,
                env=env # TODO: Not sure. Most certainly not the best solution
            )
            result = func(*a, **params)

            if json:
                return result
            elif isinstance(result, dict):
                params.update(result)
                return params
            else:
                return result
Exemplo n.º 6
0
def make_code_menu(project, pagename=None):
    """gets a list a menus for the wiki pages"""
    menu = []
    if pagename:
        # display details
        pass
    menu.append(
        {'url': url("show_tree", project=project), 'title': "Show tree"})
    menu.append(
        {'url': url('show_commits', project=project), 'title': "Show commits"})
    return(menu)
Exemplo n.º 7
0
 def test_routebuild(self):
     """ WSGI: Test route builder """
     bottle.route('/a/:b/c', name='named')(5)
     bottle.request.environ['SCRIPT_NAME'] = ''
     self.assertEqual('/a/xxx/c', bottle.url('named', b='xxx'))
     self.assertEqual('/a/xxx/c', bottle.app().get_url('named', b='xxx'))
     bottle.request.environ['SCRIPT_NAME'] = '/app'
     self.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx'))
     bottle.request.environ['SCRIPT_NAME'] = '/app/'
     self.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx'))
     bottle.request.environ['SCRIPT_NAME'] = 'app/'
     self.assertEqual('/app/a/xxx/c', bottle.url('named', b='xxx'))
Exemplo n.º 8
0
def process():
    obj = []
    codigo = request.forms.get('codigo')
    edificio = request.forms.get('edificio')
    curso = request.forms.get('curso')
    obj.append(codigo)
    obj.append(edificio)
    obj.append(curso)

    opcion = SalaUpdate(obj)
    if opcion == 1:  #exito
        redirect(url('/SalaAll') + '#exitoupdate')
    if opcion == 2:  #error en ingreso
        redirect(url('/SalaAll') + '#errorupdate')
Exemplo n.º 9
0
def delete():
    obj = []
    nombre = request.forms.get('nombre')
    semestre = request.forms.get('semestre')
    carrera = request.forms.get('carrera')
    nrc = request.forms.get('nrc')
    obj.append(nrc)
    obj.append(nombre)
    obj.append(carrera)
    obj.append(semestre)
    opcion = AsignaturaDelete(obj)
    if opcion == 1:  #exito
        redirect(url('/AsignaturaAll') + '#exito')
    if opcion == 2:  #error en ingreso
        redirect(url('/Asignatura/Eliminar/' + nrc) + '#error')
Exemplo n.º 10
0
def search_controller(terms=''):
    # This allows users without JS to search
    if request.query.terms:
        # Encoding the terms as latin1 for the Location HTTP header
        terms = request.query.terms.encode('utf-8').decode('latin1')
        destination = url("search", terms=terms)
        return redirect(destination, 303)

    # URLs are always latin1 because of WSGI, but browsers tend to send UTF-8
    terms = bytes(terms, 'latin1').decode('utf-8', errors='ignore')

    # Remove zero-width punctuation
    terms = re.sub('[\u200b-\u200d]', '', terms)

    default_sort = 'relevance'
    sort = request.query.sort
    if not sort:
        sort = default_sort

    page = get_page()
    per_page = 25

    results = package.find.search(terms, sort, page, per_page)

    other_params = {}
    if sort != default_sort:
        other_params['sort'] = sort

    data = build_data(results, page, per_page, other_params=other_params)
    data['terms'] = terms
    data['sort'] = sort

    return render('search', data)
Exemplo n.º 11
0
def simple_page(name):
    normalized_name = distlib.util.normalize_name(name)
    if name != normalized_name:
        bottle.redirect(bottle.url('simple', name=normalized_name), 301)
        return
    try:
        specs = CONFIG[name]
    except KeyError:
        bottle.abort(404)
        return
    parts = [
        '<!DOCTYPE html><html><head><meta charset="utf-8"><title>Links for ',
        name,
        '</title></head><body><h1>Links for ',
        name,
        '</h1>',
    ]
    for spec in specs:
        digest = get_file_hash('sha256', os.path.join(PACKAGES_DIR, spec))
        parts.extend([
            '<a href="{}#sha256={}">'.format(_get_package_url(spec), digest),
            spec,
            '</a><br>',
        ])
    parts.append('</body></html>')
    return ''.join(parts)
Exemplo n.º 12
0
    def post(self):
        form = SignUpForm(request.forms)
        display_form = DisplaySuccessForm(request.params)
        if not form.validate():
            return render_template(
                'www/signup.html', error=u'请求参数错误',
                display_form=display_form,
            )

        if not display_form.validate():
            return render_template(
                'www/signup.html', error=u'请求参数错误',
                display_form=display_form)

        success = display_form.data.get('success')

        try:
            account = AccountModel.create(**form.data)
            db.session.commit()
        except Exception:
            return render_template(
                'www/signup.html',
                error=u'账号已经存在',
                display_form=display_form)

        request.session['ukey'] = account.ukey
        backends.apollo.user.post(
            ukey=account.ukey, nickname=account.nickname)
        return redirect(success or url('apollo:www.main'))
Exemplo n.º 13
0
    def post(self):
        form = LoginForm(request.forms)
        display_form = DisplaySuccessForm(request.params)
        if not form.validate():
            return render_template(
                'www/signin.html', error=u'用户不存在或者密码错误',
                display_form=display_form,
            )

        if not display_form.validate():
            return render_template(
                'www/signin.html', error=u'请求参数错误',
                display_form=display_form,
            )

        data = form.data
        success = display_form.data.get('success')
        account = EmailModel.query.filter(
            EmailModel.email == data['email'],
            EmailModel.password_hash == md5.new(
                data['password_hash']).hexdigest()
        ).first()
        if not account:
            return render_template(
                'www/signin.html', error=u'用户不存在或者密码错误',
                display_form=display_form,
            )

        request.session['ukey'] = account.ukey
        return redirect(success or url('apollo:www.main'))
Exemplo n.º 14
0
def decr_proc(name):
    return run_command(
        func='decrproc',
        args=(name, ),
        message='removed one process from the {watcher} pool'.format(
            watcher=name),
        redirect_url=url('watcher', name=name))
Exemplo n.º 15
0
def connect():
    """Connects to the stats client, using the endpoint that's passed in the
    POST body.
    """
    def _ask_connection():
        return render_template('connect.html',
                               endpoints=app.discovery_thread.get_endpoints())

    if request.method == 'GET':
        return _ask_connection()

    elif request.method == 'POST':
        # if we got an endpoint in the POST body, store it.
        if request.forms.endpoint is None:
            return _ask_connection()

        endpoint_input = request.forms.endpoint
        endpoint_select = request.forms.endpoint_select

        if endpoint_select:
            endpoint = endpoint_select
        else:
            endpoint = endpoint_input

        client = connect_to_circus(endpoint)
        if not client.connected:
            set_message('Impossible to connect')

        redirect(url('index'))
Exemplo n.º 16
0
def connect():
    """Connects to the stats client, using the endpoint that's passed in the
    POST body.
    """
    def _ask_connection():
        return render_template('connect.html',
                               endpoints=app.discovery_thread.get_endpoints())

    if request.method == 'GET':
        return _ask_connection()

    elif request.method == 'POST':
        # if we got an endpoint in the POST body, store it.
        if request.forms.endpoint is None:
            return _ask_connection()

        endpoint_input = request.forms.endpoint
        endpoint_select = request.forms.endpoint_select

        if endpoint_select:
            endpoint = endpoint_select
        else:
            endpoint = endpoint_input

        client = connect_to_circus(endpoint)
        if not client.connected:
            set_message('Impossible to connect')

        redirect(url('index'))
Exemplo n.º 17
0
def note_save(note_id=None):
    s = get_session()
    if not s.get('authenticated'):
        bottle.redirect(bottle.url('login'))
    note_source = post_get('source')
    source_type = int(post_get('source_type', Note.SOURCE_TYPE_PLAINTEXT))
    db_session = Session()
    if note_id is not None:
        note = db_session.query(Note).get(note_id)
        note.source_type = source_type
        note.text = note_source
    else:
        note = Note(source=note_source, source_type=source_type)
        db_session.add(note)
    db_session.commit()
    bottle.redirect(bottle.url('note-list'))
Exemplo n.º 18
0
def get_feed():
    created = repository.creation_datetime
    updated = repository.update_datetime
    feed = {
        'id': helpers.tag_uri(host, created, repository_path),
        'self': request.url,
        'title': repository.description,
        'updated': updated,
        'entries': [
            {
                'authors': post.authors,
                'content': post.content,
                'id': helpers.tag_uri(host, post.creation_datetime, post.path.encode('utf-8')),
                'title': post.title or helpers.get_first_sentence_from_html(post.content) + ' …',
                'updated': post.update_datetime,
                'url': urljoin(
                    'http://%s:%s' % (host, port),
                    url('post', slug=quote(post.filename.encode('utf-8')))
                ),
            } for post in sorted(repository.posts, key=lambda p: \
                                     p.update_datetime, reverse=True)
        ]
    }
    response.headers['Content-Type'] = 'application/atom+xml'
    return feed
Exemplo n.º 19
0
def assert_not_banned(board):
    ip_addr = request.get("REMOTE_ADDR", "0.0.0.0")
    if IpBan.ip_is_banned(ip_addr):
        raise HTTPResponse(
            template("message.tpl", message="You are banned", redirect=url("board", board_name=board.short_name)),
            status=403,
        )
Exemplo n.º 20
0
def incr_proc(name):

    return run_command(
        func='incrproc',
        args=(name, ),
        message='added one process to the {watcher} pool'.format(watcher=name),
        redirect_url=url('watcher', name=name))
Exemplo n.º 21
0
def make_tasks_menu():
    """menus for tasks"""
    menu = []
    if is_logged():
        menu.append(
            {'url': url("add_task"), 'title': "Add tasks"})
    return(menu)
Exemplo n.º 22
0
def doStop():
    id = request.query['id']
    conn = getEc2Connection()
    instance = getEc2Instance(conn, id)
    if instance.state == RUN:
        conn.stop_instances(id)
    redirect(url('/'))
Exemplo n.º 23
0
    def test_routebuild(self):
        """ WSGI: Test route builder """

        def foo():
            pass

        bottle.route("/a/:b/c", name="named")(foo)
        bottle.request.environ["SCRIPT_NAME"] = ""
        self.assertEqual("/a/xxx/c", bottle.url("named", b="xxx"))
        self.assertEqual("/a/xxx/c", bottle.app().get_url("named", b="xxx"))
        bottle.request.environ["SCRIPT_NAME"] = "/app"
        self.assertEqual("/app/a/xxx/c", bottle.url("named", b="xxx"))
        bottle.request.environ["SCRIPT_NAME"] = "/app/"
        self.assertEqual("/app/a/xxx/c", bottle.url("named", b="xxx"))
        bottle.request.environ["SCRIPT_NAME"] = "app/"
        self.assertEqual("/app/a/xxx/c", bottle.url("named", b="xxx"))
Exemplo n.º 24
0
def add_entry():
    try:
        write_entry(request.form['title'], request.form['text'])
        flash('New entry was successfully posted')
    except sqlite3.Error as e:
        flash('There was an error: %s' % e.args[0])
    return redirect(url('show_entries'))
Exemplo n.º 25
0
def process():
    obj = []
    nombre = request.forms.get('nombre')
    semestre = request.forms.get('semestre')
    carrera = request.forms.get('carrera')
    nrc = request.forms.get('nrc')
    obj.append(nombre)
    obj.append(semestre)
    obj.append(carrera)
    obj.append(nrc)

    opcion = AsignaturaUpdate(obj)
    if opcion == 1:  #exito
        redirect(url('/AsignaturaAll') + '#exitoupdate')
    if opcion == 2:  #error en ingreso
        redirect(url('/AsignaturaAll') + '#errorupdate')
Exemplo n.º 26
0
def update_channel(id: int):
    try:
        channel = Channel.get(Channel.id == id)
        channel.update_feed()
    except Channel.DoesNotExist:
        abort(404, 'Channel does not exist')
    return redirect(url('/channels/<id:int>/items', id=channel.id))
Exemplo n.º 27
0
def post_channel():
    url = request.forms.get('url')
    Channel.create_from_url(url)
    channel = Channel.get(Channel.url == url)
    channel.save_favicon()
    channel.update_feed()
    redirect(url('/channels/<id:int>/items', id=channel.id))
Exemplo n.º 28
0
def process():
    obj = []
    nombre = request.forms.get('nombre')
    apellido = request.forms.get('apellido')
    curso = request.forms.get('curso')
    rut = request.forms.get('rut')
    obj.append(nombre)
    obj.append(apellido)
    obj.append(curso)
    obj.append(rut)

    opcion = ProfesorUpdate(obj)
    if opcion == 1:  #exito
        redirect(url('/ProfesorAll') + '#exitoupdate')
    if opcion == 2:  #error en ingreso
        redirect(url('/ProfesorAll') + '#errorupdate')
Exemplo n.º 29
0
def update_channels():
    for c in Channel.select():
        try:
            c.save_favicon()
        except :
            continue

    return redirect(url('/items'))
Exemplo n.º 30
0
def update_channels():
    for channel in Channel.select():
        try:
            channel.update_feed()
        except:
            continue

    return redirect(url('/items'))
Exemplo n.º 31
0
def edit_channel_post(id:int):
    title = request.forms.get('title')
    url = request.forms.get('url')
    channel = Channel.get(Channel.id == id)
    channel.title = title
    channel.url = url
    channel.save()
    redirect(url('/channels/<id:int>/items', id=channel.id))
Exemplo n.º 32
0
def create_domain():
    domain = request.forms.domain
    if domain:
        store = Store()
        store.create(domain)
        flash("%s added" % domain)
        fanout.update()
    return redirect(url("domains"))
Exemplo n.º 33
0
    def test_routebuild(self):
        """ WSGI: Test validate-decorator"""
        @bottle.route('/a/:b/c', name='named')
        def test(var):
            pass

        self.assertEqual('/a/xxx/c', bottle.url('named', b='xxx'))
        self.assertEqual('/a/xxx/c', bottle.app().get_url('named', b='xxx'))
Exemplo n.º 34
0
def process():
    obj = []
    semestre = request.forms.get('semestre')
    carrera = request.forms.get('carrera')
    a = semestre.split(" ")
    idd = a[1]
    obj.append(semestre)
    obj.append(carrera)
    obj.append(idd)
    opcion = HorariosCreate(obj)
    if opcion == 1:  #exito
        redirect(url('/HorariosAll') + '#exitonueva')
    if opcion == 2:  #error en ingreso
        redirect(url('/Horario/Nuevo') + '#error')
    if opcion != 1 and opcion != 2:  #error de generar horario traer conflictos
        print(opcion)
        return template('HorarioConflictos', rows=opcion)
Exemplo n.º 35
0
def person_add():
    p = Person()
    p.family_name = request.forms.family_name
    p.given_name = request.forms.given_name
    p.disabled = 0
    session.add(p)
    session.commit()
    return redirect(url("index"))
Exemplo n.º 36
0
        def wrapper(*args, **kwargs):
            if user_is_authenticated() and not request.user.is_verified:
                if request.is_ajax:
                    abort(httplib.UNAUTHORIZED, 'User is not verified')
                else:
                    redirect(url('resend_key'))

            return callback(*args, **kwargs)
Exemplo n.º 37
0
def delete_channel(id:int):
    try:
        channel = Channel.get(Channel.id == id)
        Item.delete().where(Item.channel == channel).execute()
        channel.delete_favicon()
        Channel.delete().where(Channel.id == id).execute()
    except Channel.DoesNotExist:
        abort(404, 'Channel does not exist')
    redirect(url('/'))
Exemplo n.º 38
0
def note_remove(note_id=None):
    s = get_session()
    if not s.get('authenticated') or not note_id:
        return bottle.redirect('/login')
    db_session = Session()
    note = db_session.query(Note).get(note_id)
    db_session.delete(note)
    db_session.commit()
    bottle.redirect(bottle.url('note-list'))
Exemplo n.º 39
0
def appengine_env_trigger():
    """Make a request to the app itself with the urlfetch service, so that the
    X-Appengine-Inbound-Appid header is added to the request.
    """
    url = bottle.request.url
    url = urlparse.urljoin(url, bottle.url('appengine_env_save'))
    urlfetch.fetch(url, follow_redirects=False)

    return 'OK'
Exemplo n.º 40
0
        def wrapper(*args, **kwargs):
            if (hasattr(request, 'user') and request.user is not None
                    and not request.user.is_verified):
                if request.is_ajax:
                    abort(httplib.UNAUTHORIZED, 'User is not verified')
                else:
                    redirect(url('resend_key'))

            return callback(*args, **kwargs)
Exemplo n.º 41
0
def note_remove(note_id=None):
    s = get_session()
    if not s.get('authenticated') or not note_id:
        return bottle.redirect('/login')
    db_session = Session()
    note = db_session.query(Note).get(note_id)
    db_session.delete(note)
    db_session.commit()
    bottle.redirect(bottle.url('note-list'))
Exemplo n.º 42
0
def process():
    obj = []
    codigo = request.forms.get('codigo')
    edificio = request.forms.get('edificio')
    curso = request.forms.get('curso')
    obj.append(codigo)
    obj.append(edificio)
    obj.append(curso)

    opcion = SalaCreate(obj)
    if opcion == 1:  #exito
        redirect(url('/Sala/Nuevo') + '#exito')
    if opcion == 2:  #error en ingreso
        redirect(url('/Sala/Nuevo') + '#error')
    if opcion == 3:  #error de nrc
        redirect(url('/Sala/Nuevo') + '#errornrc')

    return template('SalaNueva')
Exemplo n.º 43
0
        def wrapper(*args, **kwargs):
            if (hasattr(request, 'user') and request.user is not None and
                not request.user.is_verified):
                if request.is_ajax:
                    abort(httplib.UNAUTHORIZED, 'User is not verified')
                else:
                    redirect(url('resend_key'))

            return callback(*args, **kwargs)
Exemplo n.º 44
0
def commit_page(slug):
    content = request.POST['content']
    message = "%s changed via web interface" % unquote(slug)
    name = request.auth[0]
    email = config.get('emails', name)

    post = Post(repository_path, unquote(slug))
    if post.content != content:
        post.update_content(content, name, email, message)
    redirect(url('post', slug=slug))
Exemplo n.º 45
0
def process():
    obj = []
    nombre = request.forms.get('nombre')
    semestre = request.forms.get('semestre')
    carrera = request.forms.get('carrera')
    nrc = request.forms.get('nrc')
    obj.append(nombre)
    obj.append(semestre)
    obj.append(carrera)
    obj.append(nrc)

    opcion = AsignaturaCreate(obj)
    if opcion == 1:  #exito
        redirect(url('/Asignatura/Nueva') + '#exito')
    if opcion == 2:  #error en ingreso
        redirect(url('/Asignatura/Nueva') + '#error')
    if opcion == 3:  #error de nrc
        redirect(url('/Asignatura/Nueva') + '#errornrc')

    return template('AsignaturaNueva')
Exemplo n.º 46
0
def process():
    obj = []
    nombre = request.forms.get('nombre')
    apellido = request.forms.get('apellido')
    curso = request.forms.get('curso')
    rut = request.forms.get('rut')
    obj.append(nombre)
    obj.append(apellido)
    obj.append(curso)
    obj.append(rut)

    opcion = AlumnoCreate(obj)
    if opcion == 1:  #exito
        redirect(url('/Alumno/Nuevo') + '#exito')
    if opcion == 2:  #error en ingreso
        redirect(url('/Alumno/Nuevo') + '#error')
    if opcion == 3:  #error de nrc
        redirect(url('/Alumno/Nuevo') + '#errornrc')

    return template('AlumnoNueva')
Exemplo n.º 47
0
def note_save(note_id=None):
    s = get_session()
    if not s.get('authenticated'):
        bottle.redirect(bottle.url('login'))
    note_source = post_get('source')
    source_type = int(post_get('source_type', Note.SOURCE_TYPE_PLAINTEXT))
    is_draft = bool(post_get('is_draft', False))
    db_session = Session()
    if note_id is not None:
        note = db_session.query(Note).get(note_id)
        note.source_type = source_type
        note.is_draft = is_draft
        note.text = note_source
    else:
        note = Note(source=note_source,
                    source_type=source_type,
                    is_draft=is_draft)
        db_session.add(note)
    db_session.commit()
    bottle.redirect(bottle.url('note-list'))
Exemplo n.º 48
0
def process_upload(db):
    user_file = bottle.request.files.get('upload')
    token = bottle.request.forms.get('token')

    try:
        runs.upload(db, user_file, token)
    except:
        msg = str(sys.exc_info()[1])
        raise bottle.HTTPError(500,
                               'Error processing upload: {0:s}'.format(msg))

    return bottle.redirect(bottle.url('/'))
Exemplo n.º 49
0
def package_controller(name):
    try:
        # URLs are always latin1 because of WSGI, but browsers tend to send UTF-8
        name = bytes(name, 'latin1').decode('utf-8', errors='ignore')

        data = package.find.by_name(name)
        return render('package', data)

    except (RenamedError) as e:
        return redirect(url("package", name=e.args[0]), 301)

    except (NotFoundError) as e:
        abort(404, str(e))
Exemplo n.º 50
0
def url(this, route, **kwargs):
    """
    Pybars helper for generating a URL
    """

    new_args = {}
    for name, value in kwargs.items():
        new_args[name] = urllib.parse.quote(str(value),
                                            safe='',
                                            encoding='UTF-8',
                                            errors=None)

    return bottle.url(route, **new_args)
Exemplo n.º 51
0
        def client_or_redirect(*fargs, **fkwargs):
            if ensure_client:
                client = get_client()
                session = get_session()

                if client is None:
                    session = get_session()
                    if session.get('endpoint', None) is not None:
                        # XXX we need to pass SSH too here
                        connect_to_circus(session['endpoint'])
                    else:
                        return redirect(url('connect'))

            return func(*fargs, **fkwargs)
Exemplo n.º 52
0
def search_controller(terms=''):
    # This allows users without JS to search
    if request.query.terms:
        destination = url("search", terms=request.query.terms)
        return redirect(destination, 303)

    # URLs are always latin1 because of WSGI, but browsers tend to send UTF-8
    terms = bytes(terms, 'latin1').decode('utf-8')

    page = get_page()
    per_page = 25

    results = package.find.search(terms, page, per_page)

    data = build_data(results, page, per_page)
    data['terms'] = terms

    return render('search', data)
Exemplo n.º 53
0
def autocomplete_json():
    query = request.query.query
    branch = request.query.getall("branch")
    limit = request.query.limit
    ops_type = request.query.type
    #options = request.query.getall("options")
    id = quote(url("/search", query=query))
    response.set_header("Content-Location", id)
    # CORS header
    response.set_header("Access-Control-Allow-Origin", "*")
    response.content_type = 'application/json'
    if limit == "":
        limit = "25"
    if ops_type == "":
        ops_type = None
    if branch != "" and not set(branch).issubset(conf["indexes"].keys()):
        response.status = 422
        return {'error': 'One of your selected branches is not available for searching'}
    search = es_autocomplete(query, branch, ops_type, limit)
    if ops_type == None:
        search["type"] = "_all"
    else:
        search["type"] = ops_type
    if branch == "":
        search["branch"] = "_all"
    else:
       search["branch"] = branch
    labels = []
    for hit in search["hits"]["hits"]:
      if "label" in hit["_source"]:
        labels.append(hit["_source"]["label"][0])
      elif "title" in hit["_source"]:
        labels.append(hit["_source"]["title"][0])
      elif "prefLabel" in hit["_source"]:
        labels.append(hit["_source"]["prefLabel"][0])
    # Remove duplicates
    labels = set(labels)
    labels = list(labels)
    values = []
    for label in labels:
        values.append({"value": label})
    return dumps(values)
Exemplo n.º 54
0
def json_page(name, version_name=None):
    normalized_name = distlib.util.normalize_name(name)
    if name != normalized_name:
        kwargs = {'name': normalized_name}
        if version_name is None:
            route = 'json'
        else:
            route = 'json-version'
            kwargs['version_name'] = version_name
        bottle.redirect(bottle.url(route, **kwargs), 301)
        return

    # This magic filters directories with valid version as names, and sort
    # them according in ascending order based on its parsed version value.
    version_names = [
        vername
        for vername, _ in sorted(((vername, version) for vername, version in (
            (vername, _as_version_or_none(vername))
            for vername in os.listdir(os.path.join(JSONDATA_DIR, name)))
                                  if version is not None),
                                 key=operator.itemgetter(-1))
    ]

    # Show latest version if not specified, mimicking PyPI.
    if version_name is None:
        version_name = version_names[-1]

    data = None
    releases = collections.OrderedDict()
    for vername in version_names:
        d = _read_version_data(name, vername)
        releases[vername] = d['urls']
        if vername == version_name:
            data = d
    if data is None:
        bottle.abort(404)

    data['releases'] = releases
    return data
Exemplo n.º 55
0
def search_json(query=None):
    if query is None:
        # Get from ?q parameter instead, if exist
        query = request.query.query
        branch = request.query.getall("branch")
        limit = request.query.limit
        ops_type = request.query.type
        options = request.query.getall("options")
    fuzzy = False
    id = quote(url("/search/<query>", query=query))
    response.set_header("Content-Location", id)
    # CORS header
    response.set_header("Access-Control-Allow-Origin", "*")
    if options != None and "fuzzy" in options:
        fuzzy = True
    if limit == "":
        limit = "25"
    if ops_type == "":
        ops_type = None
    if branch != "" and not set(branch).issubset(conf["indexes"].keys()):
        response.status = 422
        return {'error': 'One of your selected branches is not available for searching'}
    search = es_search(query, branch, ops_type, limit, fuzzy)
    if ops_type == None:
        search["type"] = "_all"
    else:
        search["type"] = ops_type
    if branch == "":
        search["branch"] = "_all"
    else:
       search["branch"] = branch
    if options != None and "uris_only" in options:
      uris = []
      for hit in search["hits"]["hits"]:
          uris.append(hit["_id"])
      return {"uris": uris}
    else:
      search.pop("_shards", None)
      return search
Exemplo n.º 56
0
def verify_request_signature():
    if config.DEVELOP:
        return
    if request.path != url('callback') or request.method == 'GET':
        return

    signature = request.get_header('x-hub-signature')

    if not signature:
        logger.error("Couldn't validate the request signature.")
        abort(403, "Couldn't validate the request signature.")

    elements = signature.split('=')
    sig_hash = elements[1]

    expected_hash = hmac.new(config.FB_APP_SECRET, request.body.read(),
                             hashlib.sha1).hexdigest()

    if sig_hash != expected_hash:
        logger.info(sig_hash)
        logger.info(expected_hash)
        logger.error("Couldn't validate the request signature.")
        abort(403, "Couldn't validate the request signature.")