为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 函数参数。在

我们还可以看到状态代码是如何被覆盖的 对于POSTPUT端点,以及所有路由 在UI中使用“Books”标记进行分组。在

服务于API

最后,我们可以为API提供服务:

importuvicornuvicorn.run(app,port=9009)

浏览到http://localhost/api/1/swagger我们应该看到:

Top Level

当我们展开GET /books/{bookId}时,我们可以看到 docstring和键入中提供的信息 传递到了狂妄的用户界面。在

GET /books/{bookId}

谢谢

感谢rr-和贡献者 为优秀的 docstring-parser 包裹。在

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java计数步骤和操作   maven通过将第一个子类/jar添加到第二个子类路径,为一个子类创建jar,并为另一个子类执行goal exec:java   java JavaFX无法在ChoiceBox上调用setOnAction()?   swing使用Java,试图用图像显示JButton的可滚动列表,但显示的是文本而不是按钮   java无法读取跨行突出显示的确切文本   继承无法理解Java中super的功能   通过创建接口的模拟对象进行Java单元测试   活动布局中的java手指绘图?   java以看似随机的间隔获得NullPointerException,不知道为什么   java JButton位置不起作用   非序列化Java对象能否存储在mySQL BLob列中?   java如何使这个删除测试独立?   java Thymeleaf,无法访问该参数   java Solr CoreAware FilterFactory   java日志存储标准数据写入文件   socket上的java传递错误   java如何删除文件?   java Android有键盘小部件吗?   java方法,该方法将点对象作为参数,并根据其是否在直线段内返回true或false