zoukankan      html  css  js  c++  java
  • routes 学习

    对于routes的学习,感觉还是看官方文档理解的比较快,主要说明connect和resource

    Setting up routes

    It is assumed that you are using a framework that has preconfigured Routes for you. In Pylons, you define your routes in the make_map function in your myapp/config/routing.py module. Here is a typical configuration

    1
    2
    3
    4
    5
    6
    7
    from routes import Mapper
    map = Mapper()
    map.connect(None, "/error/{action}/{id}", controller="error")
    map.connect("home", "/", controller="main", action="index")
    # ADD CUSTOM ROUTES HERE
    map.connect(None, "/{controller}/{action}")
    map.connect(None, "/{controller}/{action}/{id}")
    

    Lines 1 and 2 create a mapper.

    Line 3 matches any three-component route that starts with “/error”, and sets the “controller” variable to a constant, so that a URL “/error/images/arrow.jpg” would produce:

    {"controller": "error", "action": "images", "id": "arrow.jpg"}
    

    Line 4 matches the single URL “/”, and sets both the controller and action to constants. It also has a route name “home”, which can be used in generation. (The other routes have None instead of a name, so they don’t have names. It’s recommended to name all routes that may be used in generation, but it’s not necessary to name other routes.)

    Line 6 matches any two-component URL, and line 7 matches any 3-component URL. These are used as catchall routes if we’re too lazy to define a separate route for every action. If you have defined a route for every action, you can delete these two routes.

    Note that a URL “/error/images/arrow.jpg” could match both line 3 and line 7. The mapper resolves this by trying routes in the order defined, so this URL would match line 3.

    If no routes match the URL, the mapper returns a “match failed” condition, which is seen in Pylons as HTTP 404 “Not Found”.

    Here are some more examples of valid routes:

    m.connect("/feeds/{category}/atom.xml", controller="feeds", action="atom")
    m.connect("history", "/archives/by_eon/{century}", controller="archives",
              action="aggregate")
    m.connect("article", "/article/{section}/{slug}/{page}.html",
              controller="article", action="view")
    

    Extra variables may be any Python type, not just strings. However, if the route is used in generation, str() will be called on the value unless the generation call specifies an overriding value.

    Other argument syntaxes are allowed for compatibility with earlier versions of Routes. These are described in the Backward Compatibility section.

    Route paths should always begin with a slash (“/”). Earlier versions of Routes allowed slashless paths, but their behavior now is undefined.

    RESTful services

    Routes makes it easy to configure RESTful web services. map.resource creates a set of add/modify/delete routes conforming to the Atom publishing protocol.

    A resource route addresses members in a collection, and the collection itself. Normally a collection is a plural word, and a member is the corresponding singular word. For instance, consider a collection of messages:

    Resource options

    The map.resource method recognizes a number of keyword args which modifies its behavior:

    controller

    Use the specified controller rather than deducing it from the collection name.

    collection

    Additional URLs to allow for the collection. Example:

    map.resource("message", "messages", collection={"rss": "GET"})
    # "GET /message/rss"  =>  ``Messages.rss()``.
    # Defines a named route "rss_messages".
    

    member

    Additional URLs to allow for a member. Example:

    map.resource('message', 'messages', member={'mark':'POST'})
    # "POST /message/1/mark"  =>  ``Messages.mark(1)``
    # also adds named route "mark_message"
    

    This can be used to display a delete confirmation form:

    map.resource("message", "messages", member={"ask_delete": "GET"}
    # "GET /message/1/ask_delete"   =>   ``Messages.ask_delete(1)``.
    # Also adds a named route "ask_delete_message".
    

    new

    Additional URLs to allow for new-member functionality.

    map.resource("message", "messages", new={"preview": "POST"})
    # "POST /messages/new/preview"
    

    path_prefix

    Prepend the specified prefix to all URL patterns. The prefix may include path variables. This is mainly used to nest resources within resources.

    name_prefix

    Prefix the specified string to all route names. This is most often combined with path_prefix to nest resources:

    map.resource("message", "messages", controller="categories",
        path_prefix="/category/{category_id}",
        name_prefix="category_")
    # GET /category/7/message/1
    # Adds named route "category_message"
    

    parent_resource

    A dict containing information about the parent resource, for creating a nested resource. It should contain the member_name and collection_name of the parent resource. This dict will be available via the associated Route object which can be accessed during a request via request.environ["routes.route"].

    If parent_resource is supplied and path_prefix isn’t, path_prefix will be generated from parent_resource as “<parent collection name>/:<parent member name>_id”.

    If parent_resource is supplied and name_prefix isn’t, name_prefix will be generated from parent_resource as “<parent member name>_”.

    Example:

    >>> m = Mapper()
    >>> m.resource('location', 'locations',
    ...            parent_resource=dict(member_name='region',
    ...                                 collection_name='regions'))
    >>> # path_prefix is "regions/:region_id"
    >>> # name prefix is "region_"
    >>> url('region_locations', region_id=13)
    '/regions/13/locations'
    >>> url('region_new_location', region_id=13)
    '/regions/13/locations/new'
    >>> url('region_location', region_id=13, id=60)
    '/regions/13/locations/60'
    >>> url('region_edit_location', region_id=13, id=60)
    '/regions/13/locations/60/edit'
    
    Overriding generated path_prefix:
    
    >>> m = Mapper()
    >>> m.resource('location', 'locations',
    ...            parent_resource=dict(member_name='region',
    ...                                 collection_name='regions'),
    ...            path_prefix='areas/:area_id')
    >>> # name prefix is "region_"
    >>> url('region_locations', area_id=51)
    '/areas/51/locations'
    
    Overriding generated name_prefix:
    
    >>> m = Mapper()
    >>> m.resource('location', 'locations',
    ...            parent_resource=dict(member_name='region',
    ...                                 collection_name='regions'),
    ...            name_prefix='')
    >>> # path_prefix is "regions/:region_id"
    >>> url('locations', region_id=51)
    '/regions/51/locations'
    map.resource("message", "messages")
    
    # The above command sets up several routes as if you had typed the
    # following commands:
    map.connect("messages", "/messages",
        controller="messages", action="create",
        conditions=dict(method=["POST"]))
    map.connect("messages", "/messages",
        controller="messages", action="index",
        conditions=dict(method=["GET"]))
    map.connect("formatted_messages", "/messages.{format}",
        controller="messages", action="index",
        conditions=dict(method=["GET"]))
    map.connect("new_message", "/messages/new",
        controller="messages", action="new",
        conditions=dict(method=["GET"]))
    map.connect("formatted_new_message", "/messages/new.{format}",
        controller="messages", action="new",
        conditions=dict(method=["GET"]))
    map.connect("/messages/{id}",
        controller="messages", action="update",
        conditions=dict(method=["PUT"]))
    map.connect("/messages/{id}",
        controller="messages", action="delete",
        conditions=dict(method=["DELETE"]))
    map.connect("edit_message", "/messages/{id}/edit",
        controller="messages", action="edit",
        conditions=dict(method=["GET"]))
    map.connect("formatted_edit_message", "/messages/{id}.{format}/edit",
        controller="messages", action="edit",
        conditions=dict(method=["GET"]))
    map.connect("message", "/messages/{id}",
        controller="messages", action="show",
        conditions=dict(method=["GET"]))
    map.connect("formatted_message", "/messages/{id}.{format}",
        controller="messages", action="show",
        conditions=dict(method=["GET"]))
    

    This establishes the following convention:

    GET    /messages        => messages.index()    => url("messages")
    POST   /messages        => messages.create()   => url("messages")
    GET    /messages/new    => messages.new()      => url("new_message")
    PUT    /messages/1      => messages.update(id) => url("message", id=1)
    DELETE /messages/1      => messages.delete(id) => url("message", id=1)
    GET    /messages/1      => messages.show(id)   => url("message", id=1)
    GET    /messages/1/edit => messages.edit(id)   => url("edit_message", id=1)
    本博客的内容如果没有标注转载字样,均属个人原创!欢迎学习交流,如果觉得有价值,欢迎转载,转载请注明出处,谢谢!
  • 相关阅读:
    JavaScript中需要注意的几个问题
    前端编码规范之JavaScript
    那些年,我们一起玩过的响应式布局
    前端编码规范之CSS
    一个不陌生的JS效果-marquee,用css3来实现
    解读jQuery中extend函数
    字体大小自适应纯css解决方案
    浅谈叶小钗面试的几个问题
    【Python开发】C和Python之间的接口实现
    【Python开发】【编程开发】各种系统的清屏操作命令
  • 原文地址:https://www.cnblogs.com/L-O-N/p/6120986.html
Copyright © 2011-2022 走看看