瓶子服务器:删除路线

如何解决瓶子服务器:删除路线

我想在我的瓶子服务器运行时添加和删除路由。

我的一般问题:是否有删除路由的正确方法?

换句话说:我该如何撤消对app.route所做的操作?

在下文中,我将更详细地描述我的问题。如果您知道我的一般问题的答案,请不要浪费时间阅读它。

这是一个演示脚本,描述了我如何解决问题:

如果致电 GET / add :添加了“ Hello World”路线

如果调用 GET / remove (获取/删除):所有具有相同前缀(例如'Hello World'路线)的路线都会触发 404错误

import bottle
from bottle import redirect,abort

def addRoute():
    app.route('/route/hello')(lambda :'Hello World')
    print('Routes after calling /add:\n' + '\n'.join([str(route) for route in app.routes]))
    redirect('route/hello')

def removeRoute():
    prefix = '/route/hello'

    #making a list of all routes having the prefix
    #because this is a testfile there is only one rule that startswith prefix
    routes = [route for route in app.routes if route.rule.startswith(prefix)]

    #because there could be multiple routes with the same rule and method,#making a list without duplicates
    ruleMethodTuples = list(dict.fromkeys([(route.rule,route.method) for route in routes]))

    for ruleMethod in ruleMethodTuples :

        #Workaround: Overwriting the existing route with a 404
        #Here I'd prefer to make a statement that removes the existing route instead,#so the default 404 would be called
        app.route(ruleMethod[0],method = ruleMethod[1])(lambda **kwords: abort(404,'Route deleted'))

    print('Routes after calling /remove:\n' + '\n'.join([str(route) for route in app.routes]))
    redirect('/route/hello')

if __name__ == '__main__':
    app = bottle.app()
    app.route('/add')(addRoute)
    app.route('/remove')(removeRoute)
    print('Initial routes:\n' + '\n'.join([str(route) for route in app.routes]))
    bottle.run(app,host = 'localhost',port = 8080)

因此,这是启动并调用后的输出:

/添加

/删除

/添加

显示每次呼叫后 app.routes 中的路由

Initial routes:
<GET '/add' <function addRoute at 0x02A876A8>>
<GET '/remove' <function removeRoute at 0x00F5F420>>
Bottle v0.12.17 server starting up (using WSGIRefServer())...
Listening on http://localhost:8080/
Hit Ctrl-C to quit.

Routes after calling /add:
<GET '/add' <function addRoute at 0x02A876A8>>
<GET '/remove' <function removeRoute at 0x00F5F420>>
<GET '/route/hello' <function addRoute.<locals>.<lambda> at 0x030C3E88>>
127.0.0.1 - - [25/Aug/2020 23:19:09] "GET /add HTTP/1.1" 303 0
127.0.0.1 - - [25/Aug/2020 23:19:09] "GET /route/hello HTTP/1.1" 200 11
Routes after calling /remove:
<GET '/add' <function addRoute at 0x02A876A8>>
<GET '/remove' <function removeRoute at 0x00F5F420>>
<GET '/route/hello' <function addRoute.<locals>.<lambda> at 0x030C3E88>>
<GET '/route/hello' <function removeRoute.<locals>.<lambda> at 0x030C3FA8>>
127.0.0.1 - - [25/Aug/2020 23:19:14] "GET /remove HTTP/1.1" 303 0
127.0.0.1 - - [25/Aug/2020 23:19:14] "GET /route/hello HTTP/1.1" 404 720
Routes after calling /add:
<GET '/add' <function addRoute at 0x02A876A8>>
<GET '/remove' <function removeRoute at 0x00F5F420>>
<GET '/route/hello' <function addRoute.<locals>.<lambda> at 0x030C3E88>>
<GET '/route/hello' <function removeRoute.<locals>.<lambda> at 0x030C3FA8>>
<GET '/route/hello' <function addRoute.<locals>.<lambda> at 0x030E0270>>
127.0.0.1 - - [25/Aug/2020 23:19:17] "GET /add HTTP/1.1" 303 0
127.0.0.1 - - [25/Aug/2020 23:19:18] "GET /route/hello HTTP/1.1" 200 11

因此,代替了 GET'/ route / hello',呼叫: app.route 使用相同的方法添加了更多路由,并且规则在列表的末尾。

到目前为止,这仍然有效,因为首先选择了最新的匹配路由,但是我敢肯定,这会(早晚)导致性能问题或在调用某些 / add后导致服务器崩溃 strong>和 /删除

我还注意到,我可以更改 app.routes 而无需更改实际路由,因此第二个问题:

我是否可以从app.routes中删除“已弃用”的路由以防止堆栈溢出?

第三个问题:

我是否正在以完全错误的方式进行操作?

解决方法

我检查了add_route的源代码

它将route添加到两个对象:self.routesself.routerapp.routesapp.router),这会带来问题。

def add_route(self,route):
    """ Add a route object,but do not change the :data:`Route.app`
        attribute."""
    self.routes.append(route)
    self.router.add(route.rule,route.method,route,name=route.name)
    if DEBUG: route.prepare()

self.router是对象Router,具有rulesbuilderstatic dyna_routesdyna_regexes

如果在添加新路线之前和之后进行检查,则会看到builderstatic中的变化。

def addRoute():
    print('--- before ---')
    print(app.router.rules)
    print(app.router.builder)
    print(app.router.static)
    print(app.router.dyna_routes)
    
    app.route('/route/hello')(lambda :'Hello World')

    print('--- after ---')
    print(app.router.rules)
    print(app.router.builder)
    print(app.router.static)
    print(app.router.dyna_routes)

    print('Routes after calling /add:\n' + '\n'.join([str(route) for route in app.routes]))
    redirect('route/hello')

如果我从'/route/hello'builder中删除了static,则'/route/hello'停止工作,但是app.routes仍然显示了它们,因此您必须删除{{1} } '/route/hello'app.routes中的}-但它们没有特殊的功能:)

app.router

我的完整代码:

def removeRoute():
    prefix = '/route/hello'

    del app.router.builder[prefix]
    del app.router.static['GET'][prefix]
    
    print('Routes after calling /remove:\n' + '\n'.join([str(route) for route in app.routes]))
    redirect('/route/hello')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-