当前位置:网站首页>Pecan — Overview
Pecan — Overview
2022-07-03 19:14:00 【Procedural ape treading on colorful auspicious clouds】
List of articles
Pecan
Pecan It is an object dispatching route (object-dispatch style routing) Lightweight of web frame .
Although it's light , but Pecan It does provide a wide range of feature sets , Can be used to build based on HTTP Applications for , Include :
Object-dispatch for easy routing
Full support for REST-style controllers
Extensible security framework
Extensible template language support
Extensible JSON support
Easy Python-based configuration
@expose()
If a method is @expose() decorate , that Pecan The corresponding request will be routed to this method .
Example :
from pecan import expose
class RootController(object):
@expose('json')
def hello(self):
return {
'msg': 'Hello!'}
When accessing /hello when , Returns the {'msg': 'Hello!'} To the client .
@expose Parameters of “json”, Appoint content_type by application/json. If you don't specify ,content_type The default is text/html.
route
Pecan Use what is called object distribution (object-dispatch) The routing strategy of (routing strategy) take HTTP Request mapping to controller , Then call back the method . Object distribution first splits the path into component lists , Then traverse the object path from the root controller .
Example :
from pecan import expose
class BooksController(object):
@expose()
def index(self):
return "Welcome to book section."
@expose()
def bestsellers(self):
return "We have 5 books in the top 10."
class CatalogController(object):
@expose()
def index(self):
return "Welcome to the catalog."
books = BooksController()
class RootController(object):
@expose()
def index(self):
return "Welcome to store.example.com!"
@expose()
def hours(self):
return "Open 24/7 on the web."
catalog = CatalogController()
Online store pair /catalog/books/bestsellers The requests are divided into catalog,books and bestsellers. Next ,Pecan Will find on the root controller catalog. And then in catalog Object books, In the end in books Find bestsellers Method .
route :
└── /
├── /hours
└── /catalog
└── /catalog/books
└── /catalog/books/bestsellers
Route to the following controller methods according to the path :
└── RootController.index
├── RootController.hours
└── CatalogController.index
└── BooksController.index
└── BooksController.bestsellers
Use generic Controller Write API
In the following example , Use ordinary Python objects creating controller.
When GET / When asked to come in , Will be routed to RootController Of index Method . And this index Method is @expose(generic=True, template='json') decorate , stay expose Internally generated @index.when. here , If the request path is the same , But the request method is different , that Pecan According to the request method, the request will be routed to the corresponding @index.when Method of decoration .
from pecan import abort, expose
# Note: this is *not* thread-safe. In real life, use a persistent data store.
BOOKS = {
'0': 'The Last of the Mohicans',
'1': 'Catch-22'
}
class BookController(object):
def __init__(self, id_):
self.id_ = id_
assert self.book
@property
def book(self):
if self.id_ in BOOKS:
return dict(id=self.id_, name=BOOKS[self.id_])
abort(404)
# HTTP GET /<id>/
@expose(generic=True, template='json')
def index(self):
return self.book
# HTTP PUT /<id>/
@index.when(method='PUT', template='json')
def index_PUT(self, **kw):
BOOKS[self.id_] = kw['name']
return self.book
# HTTP DELETE /<id>/
@index.when(method='DELETE', template='json')
def index_DELETE(self):
del BOOKS[self.id_]
return dict()
class RootController(object):
@expose()
def _lookup(self, id_, *remainder):
return BookController(id_), remainder
# HTTP GET /
@expose(generic=True, template='json')
def index(self):
return [dict(id=k, name=v) for k, v in BOOKS.items()]
# HTTP POST /
@index.when(method='POST', template='json')
def index_POST(self, **kw):
id_ = str(len(BOOKS))
BOOKS[id_] = kw['name']
return dict(id=id_, name=kw['name'])
Use RestController Write API
Pecan Provide RestController, Developers can inherit this class to create controller.
from pecan import expose
from pecan.rest import RestController
from mymodel import Book
class BooksController(RestController):
@expose()
def get(self, id):
book = Book.get(id)
if not book:
abort(404)
return book.title
RestController Provide the following mapping .
for example :GET /books/1 The request will be routed to get_one Method .
| Method | Description | Example Method(s) / URL(s) |
|---|---|---|
| get_one | Display one record. | GET /books/1 |
| get_all | Display all records in a resource. | GET /books/ |
| get | A combo of get_one and get_all. | GET /books/ GET /books/1 |
| new | Display a page to create a new resource. | GET /books/new |
| edit | Display a page to edit an existing resource. | GET /books/1/edit |
| post | Create a new record. | POST /books/ |
| put | Update an existing record. | POST /books/1?_method=put |
| PUT /books/1 | ||
| get_delete | Display a delete confirmation page. | GET /books/1/delete |
| delete | Delete an existing record. | POST /books/1?_method=delete DELETE /books/1 |
If you need to customize the method, you can define _custom_actions.
The following example : request POST /books/checkout Will be routed to BooksController Of checkout Method .
from pecan import expose
from pecan.rest import RestController
from mymodel import Book
class BooksController(RestController):
_custom_actions = {
'checkout': ['POST']
}
@expose()
def checkout(self, id):
book = Book.get(id)
if not book:
abort(404)
book.checkout()
边栏推荐
- 【数学建模】基于matlab船舶三自由度MMG模型【含Matlab源码 1925期】
- Common PostgreSQL commands
- 2020 intermediate financial management (escort class)
- Differential constrained SPFA
- EGO Planner代码解析bspline_optimizer部分(3)
- How can I avoid "div/0!" Errors in Google Docs spreadsheet- How do I avoid the '#DIV/0!' error in Google docs spreadsheet?
- How to build an efficient information warehouse
- [wallpaper] (commercially available) 70 wallpaper HD free
- Flutter网络和数据存储框架搭建 -b1
- math_ Taylor formula
猜你喜欢

leetcode:556. 下一个更大元素 III【模拟 + 尽可能少变更】

In addition to the prickles that pierce your skin, there are poems and distant places that originally haunt you in plain life

SSM integration - joint debugging of front and rear protocols (list function, add function, add function status processing, modify function, delete function)

Dart JSON编码器和解码器剖析

FBI warning: some people use AI to disguise themselves as others for remote interview

A green plug-in that allows you to stay focused, live and work hard
![[leetcode周赛]第300场——6110. 网格图中递增路径的数目-较难](/img/8d/0e515af6c17971ddf461e3f3b87c30.png)
[leetcode周赛]第300场——6110. 网格图中递增路径的数目-较难

Thesis study - 7 Very Deep Convolutional Networks for Large-Scale Image Recognition (3/3)
![[wallpaper] (commercially available) 70 wallpaper HD free](/img/21/6802da1056a18157b15de85df60cf5.jpg)
[wallpaper] (commercially available) 70 wallpaper HD free

组策略中开机脚本与登录脚本所使用的用户身份
随机推荐
平淡的生活里除了有扎破皮肤的刺,还有那些原本让你魂牵梦绕的诗与远方
Free year-end report summary template Welfare Collection
DriveSeg:动态驾驶场景分割数据集
A green plug-in that allows you to stay focused, live and work hard
Differential constrained SPFA
How to read the source code [debug and observe the source code]
leetcode:11. Container with the most water [double pointer + greed + remove the shortest board]
How to design a high concurrency system
我们做了一个智能零售结算平台
Record: writing MySQL commands
[disease identification] machine vision lung cancer detection system based on Matlab GUI [including Matlab source code 1922]
leetcode:11. 盛最多水的容器【双指针 + 贪心 + 去除最短板】
Using the visualization results, click to appear the corresponding sentence
Record: pymysql is used in pycharm to connect to the database
If the warehouse management communication is not in place, what problems will occur?
Pytorch introduction to deep learning practice notes 13- advanced chapter of cyclic neural network - Classification
Scrapy爬虫框架
达梦数据库的物理备份和还原简解
SQL: special update operation
利用可视化结果,点击出现对应的句子