为bareASGI提供休息支持
bareasgi-rest的Python项目详细描述
bareASGI休息
这个包为writing REST提供了增强的支持 具有bareASGI的API, (阅读docs)。在
它包括:
- 简化REST API创建的路由器
- 一个夸张的API端点
这是一个python3.7+包,目前是预发布版本。在
安装
这个包可以从pypi安装。在
它目前是预发行版,因此您需要--pre标志。在
$ pip install --pre bareASGI-rest
运行代码需要一个ASGI服务器。以下示例使用 uvicorn。在
^{pr2}$使用
此包提供的路由器映射参数和 请求处理程序的类型。在
我们将创建一个模拟图书存储库。在
创建键入词典
这是一本书的类型。我们使用TypedDict
来允许自动类型发现
fromdatetimeimportdatetimetry:# Available in 3.8fromtypingimportTypedDict# type:ignoreexcept:# Available in 3.7fromtyping_extensionsimportTypedDictclassBook(TypedDict):"""A Book Args: book_id (int): The book id title (str): The title author (str): The author published (datetime): The publication date """book_id:inttitle:strauthor:strpublished:datetime
注意:docstring将用于为swagger提供文档。在
创建API
现在我们可以构建API了。在
fromtypingimportDict,Listfromurllib.errorimportHTTPErrorBOOKS:Dict[int,Book]={}NEXT_ID:int=0asyncdefget_books()->List[Book]:"""Get all the books. This method gets all the books in the shop. Returns: List[Book]: All the books """returnlist(BOOKS.values())asyncdefget_book(book_id:int)->Book:"""Get a book for a given id Args: book_id (int): The id of the book Raises: HTTPError: 404, when a book is not found Returns: Book: The book """ifbook_idnotinBOOKS:raiseHTTPError(None,404,None,None,None)returnBOOKS[book_id]asyncdefcreate_book(author:str,title:str,published:datetime)->int:"""Add a book Args: author (str): The author title (str): The title published (datetime): The publication date Returns: int: The id of the new book """NEXT_ID+=1BOOKS[NEXT_ID]=Book(book_id=NEXT_ID,title=title,author=author,published=published)returnNEXT_IDasyncdefupdate_book(book_id:int,author:str,title:str,published:datetime)->None:"""Update a book Args: book_id (int): The id of the book to update author (str): The new author title (str): The title published (datetime): The publication date Raises: HTTPError: 404, when a book is not found """ifbook_idnotinBOOKS:raiseHTTPError(None,404,None,None,None)BOOKS[book_id]['title']=titleBOOKS[book_id]['author']=authorBOOKS[book_id]['published']=published
我们可以看到错误是通过引发HTTPError来处理的
来自urllib.errors
标准库包。已经应用了一种惯例,即状态代码必须
出现在邮件前面,用逗号分隔。在
添加对REST路由器的支持
现在我们必须创建应用程序并添加对路由器的支持。在
frombareasgiimportApplicationfrombareasgi_restimportRestHttpRouter,add_swagger_uirouter=RestHttpRouter(None,title="Books",version="1",description="A book api",base_path='/api/1',tags=[{'name':'Books','description':'The book store API'}])app=Application(http_router=router)add_swagger_ui(app)
注意base_path
参数可用于给all加前缀
路径。在
RestHttpRouter
是基本路由器的一个子类,因此
所有这些方法都是可用的。在
创建路由
现在我们可以创建路由:
tags=['Books']router.add_rest({'GET'},'/books',get_books,tags=tags)router.add_rest({'GET'},'/books/{bookId:int}',get_book,tags=tags)router.add_rest({'POST'},'/books',create_book,tags=tags,status_code=201)router.add_rest({'PUT'},'/books/{bookId:int}',update_book,tags=tags,status_code=204)
首先,我们应该注意到路径的前缀是
base_path
提供给路由器。在
回顾一下get_book
的实现,我们可以
请注意camel case path变量bookId
已经
映射到snake casebook_id
参数。在create_book
的主体中提供的JSON对象将
类似地,将camel cased属性映射到snake cased
函数参数。在
我们还可以看到状态代码是如何被覆盖的
对于POST
和PUT
端点,以及所有路由
在UI中使用“Books”标记进行分组。在
服务于API
最后,我们可以为API提供服务:
importuvicornuvicorn.run(app,port=9009)
浏览到http://localhost/api/1/swagger我们应该看到:
当我们展开GET /books/{bookId}
时,我们可以看到
docstring和键入中提供的信息
传递到了狂妄的用户界面。在
谢谢
感谢rr-和贡献者 为优秀的 docstring-parser 包裹。在
- 项目
标签: