tornado的路由分发

1

from tornado.httpserver import HTTPServer
from tornado.httputil import HTTPServerConnectionDelegate, HTTPMessageDelegate, ResponseStartLine, HTTPHeaders
from tornado.routing import RuleRouter, Rule, PathMatches
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop

‘‘‘
RuleRouter([Rule的实例1,Rule的实例2])
‘‘‘

‘‘‘
第一种
Rule(Matcher,HTTPServerConnectionDelegate)
‘‘‘

class MessageDelegate(HTTPMessageDelegate):
    def __init__(self, connection):
        self.connection = connection

    def finish(self):
        self.connection.write_headers(
            ResponseStartLine("HTTP/1.1", 200, "OK"),  # HTTP响应的状态行
            HTTPHeaders({"Content-Length": "2", "k": ‘V‘}),  # Response Headers 响应头部
            b"OK")  # 响应body
        self.connection.finish()

class ConnectionDelegate(HTTPServerConnectionDelegate):
    def start_request(self, server_conn, request_conn):
        print(server_conn, request_conn)
        return MessageDelegate(request_conn)

router = RuleRouter([
    Rule(PathMatches("/handler"), ConnectionDelegate()),
    # ... more rules
])

if __name__ == ‘__main__‘:
    server = HTTPServer(router)
    server.listen(8888)
    IOLoop.current().start()
from tornado.httpserver import HTTPServer
from tornado.httputil import HTTPServerConnectionDelegate, HTTPMessageDelegate, ResponseStartLine, HTTPHeaders,     HTTPServerRequest
from tornado.routing import RuleRouter, Rule, PathMatches, Router
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop
import tornado.template

‘‘‘
RuleRouter([Rule的实例1,Rule的实例2])
‘‘‘

‘‘‘
第二种
Rule(Matcher,Router实例)
Router实例本质还是提供一个 HTTPMessageDelegate去处理
‘‘‘

class MessageDelegate(HTTPMessageDelegate):
    def __init__(self, connection):
        self.connection = connection

    def finish(self):
        self.connection.write_headers(
            ResponseStartLine("HTTP/1.1", 200, "OK"),
            HTTPHeaders({"Content-Length": "2"}),
            b"OK")
        self.connection.finish()

class CustomRouter(Router):
    def find_handler(self, request, **kwargs):
        # some routing logic providing a suitable HTTPMessageDelegate instance
        print(type(request))  # HTTPServerRequest
        print(request.connection)
        return MessageDelegate(request.connection)

router = RuleRouter([
    Rule(PathMatches("/router.*"), CustomRouter())
])

if __name__ == ‘__main__‘:
    server = HTTPServer(router)
    server.listen(8888)
    IOLoop.current().start()

路由分发APP

from tornado.httpserver import HTTPServer
from tornado.routing import RuleRouter, Rule, PathMatches, Router
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop

class Handler1(RequestHandler):
    def get(self):
        self.write(‘1‘)

class Handler2(RequestHandler):
    def get(self):
        self.write(‘2‘)

app1 = Application([
    (r"/app1/handler", Handler1),
    # other handlers ...
])

app2 = Application([
    (r"/app2/handler", Handler2),
    # other handlers ...
])

router = RuleRouter([
    Rule(PathMatches("/app1.*"), app1),
    Rule(PathMatches("/app2.*"), app2)
])

if __name__ == ‘__main__‘:
    server = HTTPServer(router)
    server.listen(8888)
    IOLoop.current().start()

根据域名匹配

from tornado.httpserver import HTTPServer
from tornado.routing import RuleRouter, Rule, PathMatches, Router, HostMatches
from tornado.web import RequestHandler, Application
from tornado.ioloop import IOLoop

class Handler1(RequestHandler):
    def get(self):
        self.write(‘1‘)

router = RuleRouter([
    Rule(HostMatches(‘monitor.com‘),
         RuleRouter([Rule(PathMatches(‘/app1.*‘), Application([(r‘/app1/handler1‘, Handler1)]))])),
    Rule(HostMatches(‘test.monitor.com‘),
         RuleRouter([Rule(PathMatches(‘/app1.*‘), Application([(r‘/app1/handler1‘, Handler1)]))])),
])

if __name__ == ‘__main__‘:
    server = HTTPServer(router)
    server.listen(8888)
    IOLoop.current().start()

原文地址:https://www.cnblogs.com/liuer-mihou/p/11963639.html

时间: 2024-10-08 02:34:22

tornado的路由分发的相关文章

Django-urls路由分发

例如:127.0.0.0:8000/blog/lucaq.html,当有多个应用时,需要在blog应用下进行路由,我们在blog应用下做一个urls路由分发,就需要include模块实现. 导入include模块 分组: 引入include,在blog路径后加分组,Blog为应用名,urls为Blog下的urls,当路径为blog时,自动分发到Blog这个组,并将/blog/后面的路径传到Blog组,下图为Blog.urls配置 这边也建一个路由分发,拿到分发过来的路径后,正则匹配拿到路径,给这

Magento路由分发过程解析(二):Standard路由对象(转)

本文主要关注Magento的standard路由对象中的Mage_Core_Controller_Varien_Router_Standard::match()方法,该方法在前端控制器中调用,主要用来检查当前请求的URL地址,并决定匹配的模块,控制器以及方法,并且最后调用控制器分发该方法. 对于在上篇文章前端控制器循环所有的路由器来说,该方法完成了以下任务, 路由对象提供match()方法,并检测请求对象,如果匹配,则该路由对象获取该请求. 将请求标记为已分发. 设置请求对象. 假设没有找到匹配

tornado3第二部分分析tornado处理路由__call__()

tornado有许多关于如何处理路由列表的源码分析的博客,关键在与调用了Application.__call__函数,然后遍历路由列表,取出对应的处理类,由于处理类都是RequestHandler类,调用的是父类的_excute()进行响应处理,我们要了解的是__call__函数和什么时候调用了__call__函数 def __call__(self, request):         """Called by HTTPServer to execute the reque

MVC框架-路由分发总结

原网址将会不断更新 :   作程的技术博客  <MVC框架-路由分发总结> it.zuocheng.net 路由的类型 Route Type 无路由 No Route HTTP请求直接定位到特定的脚本文件执行.比如http://domain/news/latest.php 动态路由 依据某种动态规则进行路由和分发,一般有如下形式: 强约束URL 将Class,function 等信息隐藏在url中,请求来时,依据规则解析URL就可以定位Action函数,比如http://domain/mode

Admin注册和路由分发详解

1.启动 #autodiscover_modules('admin', register_to=site) 2.注册 1.单例对象 admin.site = AdminSite(): 单例对象 AdminSite 源码: class AdminSite(object): def __init__(self, name='admin'): self._registry = {} def register(self, model, admin_class=None, **options): if n

django之路由分发

路由分发决定哪一个路由由哪一个视图函数来处理. 注意:django2.0里的re_path和django1.0里的url除了名字不一样,其他都一样. 简单配置 from django.urls import path,re_path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('timer/',views.timer), # 路由配置: 决定哪一个路由由哪一个视图函数来处理 # rep

一、虚拟环境.二、路由配置主页与404.三、2.x路由分发.四、伪静态.五、request对象.六、FBV与CBV.七、文件上传.

一.虚拟环境 ''' 解决版本共存 1. 用pycharm选择File点击NewProject然后选择virtualenv创建一个纯净环境 2. 打开下载的目录将venv文件夹下的所有文件(纯净的环境)copy到需要指定长期使用的文件夹下 3. 再次创建项目时,将该环境(指定长期使用的文件夹下Scripts文件夹中的python.exe文件)添加到pycharm环境选择(System Interpreter)中 4. 为该环境添加需要处理的版本共存包 ''' 二.路由配置主页与404 ''' 路

一、数据库表中字段的增删改查,二、路由基础.三、有名无名分组.四、多app共存的路由分配.五、多app共存时模板冲突问题.六、创建app流程.七、路由分发.八、路由别名,九、名称空间.十、反向解析.十一、2.x新特性.十二、自定义转换器

一.数据库表中字段的增删改查 ''' 直接在modules中对字段进行增删改查 然后在tools下点击Run manage.py Task执行makemigrations和migrate 注意在执行字段的删除过程中需不需要对数据进行备份 ''' 二.路由基础 ''' # url中含有四个参数 # url(regex, view, kwargs=None, name=None) # 正则路径 视图函数地址 默认关键字参数(了解) 路由别名 # r'index' 只要请求中含有index都可以匹配成

stark组件前戏(3)之django路由分发的本质include

django路由分发的三张方式 方式一: from django.urls import re_path, include urlpatterns = [ re_path(r'^web/', include('app01:urls')), ] include的返回值: return (urlconf_module, app_name, namespace) 方式二: # include函数主要返回有三个元素的一个元组. # app01/urls.py urlpatterns = [ re_pat