How to use the bottle.abort function in bottle

To help you get started, we’ve selected a few bottle examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Jwink3101 / NBweb / NBweb / main.py View on Github external
if not item['rootbasename'].endswith('/'):
            item['rootbasename'] += '/'
        item['rootname'] = item['rootbasename'] 
        item['meta_title'] = os.path.split(parts.rootdirname)[-1]

        db.close()
        return fill_template(item,show_path=True,isdir=True)
    else:
        refresh = float( request.query.get('refresh',default=-1) )
        
        force = request.query.get('forcereload','false').lower() == 'true'
        item = parse_path(systemname,db,force=force)

        # drafts. Must be logged in as an edit_user
        if item['draft'] and not is_edit_user:
            abort(401)

        item['crossref'] = cross_ref(item,db)
        
        db.close()
        return fill_template(item,show_path=True,refresh=refresh)
github nfvlabs / openmano / openmano / httpserver.py View on Github external
@bottle.route(url_base + '//scenarios/', method='PUT')
def http_put_scenario_id(tenant_id, scenario_id):
    '''edit an existing scenario id'''
    print "http_put_scenarios by tenant " + tenant_id 
    http_content,_ = format_in( scenario_edit_schema )
    #r = utils.remove_extra_items(http_content, scenario_edit_schema)
    #if r is not None: print "http_put_scenario_id: Warning: remove extra items ", r
    print "http_put_scenario_id input: ",  http_content
    
    result, data = nfvo.edit_scenario(mydb, tenant_id, scenario_id, http_content)
    if result < 0:
        print "http_put_scenarios error %d %s" % (-result, data)
        bottle.abort(-result, data)
    else:
        #print json.dumps(data, indent=4)
        #return format_out(data)
        return http_get_scenario_id(tenant_id,data)
github Jwink3101 / NBweb / NBweb / main.py View on Github external
def run_gc_web():
    """
    Run garbage collection and display memory before and after. NOT perfect
    and will show if more than one NBweb is running at a time
    """
    # Get login and session
    logged_in,session = check_logged_in()
    if not logged_in:
        redirect('/_login/_gc') # Shouldn't get here w/o being logged in but just in case
    elif session.get('name','') not in NBCONFIG.edit_users:
        abort(401)


    cmd = 'ps -u {} -o rss,etime,pid,command|grep {} |grep -v grep'.format(os.environ['USER'],NBCONFIG.source)
    response.content_type = 'text/text; charset=UTF8' # Just raw text
    p1 = subprocess.check_output(cmd,shell=True)
    yield utils.to_unicode(p1) + '\n'
    gc.collect()
    p2 = subprocess.check_output(cmd,shell=True)
    yield utils.to_unicode(p2) + '\n'
github Jwink3101 / NBweb / NBweb / main.py View on Github external
map_view is used ONLY for the sitemap. Calling with other pages may
    not work as expected
    """
    # Is it an index.ext page? Remove that!
    parts = utils.fileparts(rootpath)
    if parts.basename == 'index': # Folder pages. Will handle index page text later
        if parts.dirname != '':
            redirect('/'+parts.dirname + '/')
        else:
            redirect('/')

    original_ext = parts.ext

    # No special pages here!
    if any(rootpath.startswith(r) for r in ['/_','_']):
        abort(403)

    # Get the systemname. Will add '/' for dir and abort if not found
    # Will also handle files vs dirs with the same base name
    systemname = get_systemname(rootpath,auto_abort=True)

    isdir = systemname.endswith('/')

    if isdir and not rootpath.endswith('/'): # We want directories to end with '/'
        redirect('/'+ rootpath + '/') # From the above, we know index.ext is removed

    parts = utils.fileparts(systemname,root=NBCONFIG.source) # Will handle it differently if ends with /

    # Get login and session
    logged_in,session = check_logged_in()
    is_edit_user = session.get('name','') in NBCONFIG.edit_users
github vheon / JediHTTP / jedihttp / hmac_plugin.py View on Github external
def wrapper(*args, **kwargs):
            if not is_local_request():
                self._logger.info('Dropping request with bad Host header.')
                abort(httplib.UNAUTHORIZED,
                      'Unauthorized, received request from non-local Host.')
                return

            if not self.is_request_authenticated():
                self._logger.info('Dropping request with bad HMAC.')
                abort(httplib.UNAUTHORIZED, 'Unauthorized, received bad HMAC.')
                return

            body = callback(*args, **kwargs)
            self.sign_response_headers(response.headers, body)
            return body
        return wrapper
github nfvlabs / openvim / httpserver.py View on Github external
if net_type!="bridge_man" and net_type!="bridge_data":
                    bottle.abort(HTTP_Bad_Request, "Only 'bridge_man' or 'bridge_data' net types can be bound to 'bridge', 'macvtap' or 'default")
            else:
                net_type='bridge_man'
    
    if net_type==None:
        net_type='bridge_man' 
        
    if net_provider != None:
        if net_provider[:7]=='bridge:':
            #check it is one of the pre-provisioned bridges
            bridge_net_name = net_provider[7:]
            for brnet in config_dic['bridge_nets']:
                if brnet[0]==bridge_net_name: # free
                    if brnet[3] != None:
                        bottle.abort(HTTP_Conflict, "invalid 'provider:physical', bridge '%s' is already used" % bridge_net_name)
                        return
                    bridge_net=brnet
                    net_vlan = brnet[1]
                    break
#            if bridge_net==None:     
#                bottle.abort(HTTP_Bad_Request, "invalid 'provider:physical', bridge '%s' is not one of the provisioned 'bridge_ifaces' in the configuration file" % bridge_net_name)
#                return
    elif net_type=='bridge_data' or net_type=='bridge_man':
        #look for a free precreated nets
        for brnet in config_dic['bridge_nets']:
            if brnet[3]==None: # free
                if bridge_net != None:
                    if net_type=='bridge_man': #look for the smaller speed
                        if brnet[2] < bridge_net[2]:   bridge_net = brnet
                    else: #look for the larger speed
                        if brnet[2] > bridge_net[2]:   bridge_net = brnet
github Juniper / contrail-server-manager / src / server_mgr_main.py View on Github external
def process_dhcp_event(self):
        action = bottle.request.query.action
        entity = bottle.request.json
        try:
            self._serverDb.server_discovery(action, entity)
        except Exception as e:
            self.log_trace()
            abort(404, repr(e))
        return entity
    # end process_dhcp_event
github PyJaipur / PyJudge / server.py View on Github external
def createSession(username):
    try:
        session = Session.create(user=User.get(User.username == username))
    except IntegrityError:
        return bottle.abort(500, "Error! Please try again.")
    bottle.response.set_cookie(
        "s_id",
        session.token,
        expires=datetime.datetime.now() + datetime.timedelta(days=30),
    )
    return bottle.redirect("/dashboard")
github nfvlabs / openmano / openvim / httpserver.py View on Github external
bottle.abort(HTTP_Not_Acceptable, 'Content-Type ' + str(format_type) + ' not supported.')
            return
        #if client_data == None:
        #    bottle.abort(HTTP_Bad_Request, "Content error, empty")
        #    return
        #check needed_items

        #print "HTTP input data: ", str(client_data)
        error_text = "Invalid content "
        js_v(client_data, schema)

        return client_data
    except (ValueError, yaml.YAMLError) as exc:
        error_text += str(exc)
        print error_text 
        bottle.abort(HTTP_Bad_Request, error_text)
    except js_e.ValidationError as exc:
        print "HTTP validate_in error, jsonschema exception ", exc.message, "at", exc.path
        print "  CONTENT: " + str(bottle.request.body.readlines())
        error_pos = ""
        if len(exc.path)>0: error_pos=" at '" +  ":".join(map(str, exc.path)) + "'"
        bottle.abort(HTTP_Bad_Request, error_text + error_pos+": "+exc.message)
    #except:
github crs4 / pyEHR / services / queryservice.py View on Github external
def _error(self, msg, error_code):
        self.logger.error(msg)
        body = {
            'SUCCESS': False,
            'ERROR': msg
        }
        abort(error_code, json.dumps(body))