当前位置:网站首页>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()
边栏推荐
- Change is the eternal theme
- What does a really excellent CTO look like in my eyes
- Hard disk monitoring and analysis tool: smartctl
- Work Measurement - 1
- Free year-end report summary template Welfare Collection
- shell 脚本中关于用户输入参数的处理
- Simple solution of physical backup and restore of Damon database
- EGO Planner代码解析bspline_optimizer部分(3)
- Record: pymysql is used in pycharm to connect to the database
- This Chinese numpy quick look-up table is too easy!
猜你喜欢
Leetcode: 11. Récipient contenant le plus d'eau [double pointeur + cupidité + enlèvement de la plaque la plus courte]
Using the visualization results, click to appear the corresponding sentence
2020 intermediate financial management (escort class)
In addition to the prickles that pierce your skin, there are poems and distant places that originally haunt you in plain life
SQL injection for Web Security (1)
Analysis of dart JSON encoder and decoder
FBI警告:有人利用AI换脸冒充他人身份进行远程面试
[leetcode] [SQL] notes
ActiveMQ的基础
Record the errors reported when running fluent in the simulator
随机推荐
TFs and SVN [closed] - TFs vs SVN [closed]
2022.02.11
我們做了一個智能零售結算平臺
my. INI file not found
Ego planner code parsing Bspline_ Optimizer section (3)
shell 脚本中关于用户输入参数的处理
How does if ($variable) work? [repeat] - how exactly does if ($variable) work? [duplicate]
The earliest record
Record: pymysql is used in pycharm to connect to the database
EGO Planner代碼解析bspline_optimizer部分(1)
[optics] vortex generation based on MATLAB [including Matlab source code 1927]
HOW TO WRITE A DAILY LAB NOTE?
Thesis study - 7 Very Deep Convolutional Networks for Large-Scale Image Recognition (3/3)
Suffix derivation based on query object fields
The most valuable thing
Counting from the East and counting from the West will stimulate 100 billion industries. Only storage manufacturers who dare to bite the "hard bone" will have more opportunities
Analysis of dart JSON encoder and decoder
Floating source code comment (38) parallel job processor
Free year-end report summary template Welfare Collection
235. Ancêtre public le plus proche de l'arbre de recherche binaire [modèle LCA + même chemin de recherche]