当前位置:网站首页>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()
边栏推荐
- Processing of user input parameters in shell script
- Streaming media server (16) -- figure out the difference between live broadcast and on-demand
- How to read the source code [debug and observe the source code]
- Dart JSON编码器和解码器剖析
- Analyse du Code du planificateur ego bspline Section Optimizer (1)
- HOW TO WRITE A DAILY LAB NOTE?
- Briefly describe the quantitative analysis system of services
- “google is not defined” when using Google Maps V3 in Firefox remotely
- Comments on flowable source code (37) asynchronous job processor
- Hard disk monitoring and analysis tool: smartctl
猜你喜欢

ActiveMQ的基础

Record the errors reported when running fluent in the simulator

Help change the socket position of PCB part

Free year-end report summary template Welfare Collection

The online customer service system developed by PHP is fully open source without encryption, and supports wechat customer service docking
![[free sharing] kotalog diary2022 plan electronic manual ledger](/img/ca/1ffbfcc16e3019261f70274a89c16f.jpg)
[free sharing] kotalog diary2022 plan electronic manual ledger

Compose LazyColumn 顶部添加控件

Verilog HDL continuous assignment statement, process assignment statement, process continuous assignment statement

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

235. 二叉搜索树的最近公共祖先【lca模板 + 找路径相同】
随机推荐
Streaming media server (16) -- figure out the difference between live broadcast and on-demand
How does if ($variable) work? [repeat] - how exactly does if ($variable) work? [duplicate]
Free hand account sharing in September - [cream Nebula]
Hard disk monitoring and analysis tool: smartctl
leetcode:556. Next larger element III [simulation + change as little as possible]
I didn't cancel
235. 二叉搜索樹的最近公共祖先【lca模板 + 找路徑相同】
Thesis study - 7 Very Deep Convolutional Networks for Large-Scale Image Recognition (3/3)
【光学】基于matlab介电常数计算【含Matlab源码 1926期】
Know what it is, and know why, JS object creation and inheritance [summary and sorting]
Record the errors reported when running fluent in the simulator
Recommend a GIF processing artifact less than 300K - gifsicle (free download)
Day18 - basis of interface testing
[disease identification] machine vision lung cancer detection system based on Matlab GUI [including Matlab source code 1922]
SSM integration - joint debugging of front and rear protocols (list function, add function, add function status processing, modify function, delete function)
EGO Planner代碼解析bspline_optimizer部分(1)
01. Preparation for automated office (free guidance, only three steps)
Change is the eternal theme
Common PostgreSQL commands
Does SQL always report foreign key errors when creating tables?