欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python進行Restful?API開發(fā)實例詳解

 更新時間:2022年03月30日 10:09:16   作者:Bulut0907  
這篇文章主要介紹了Python進行Restful?API開發(fā)實例,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1. Flask-RESTful

1.安裝pip依賴

[root@bigdata001 ~]#
[root@bigdata001 ~]# pip3 install flask
[root@bigdata001 ~]#
[root@bigdata001 ~]# pip3 install flask_restful
[root@bigdata001 ~]#

2.運行程序如下:

#!/usr/bin/python3
from flask import Flask
from flask_restful import Resource, Api, reqparse
host = '0.0.0.0'
port = 5600
app = Flask(__name__)
api = Api(app)
class HelloWorld(Resource):
    def __init__(self):
        self.parser = reqparse.RequestParser()
        self.parser.add_argument("key1", type = str)
        self.parser.add_argument("key2", type = str)
    def get(self):
        data = self.parser.parse_args()
        value1 = data.get("key1")
        value2 = data.get("key2")
        return {'hello':'world', value1:value2}
api.add_resource(HelloWorld, '/query')
if __name__ == '__main__':
    app.run(host = host, port = port, debug = True)

3.請求URL: http://192.168.23.21:5600/query?key1=fruit&key2=apple

4.查看Web頁面返回結(jié)果如下:

{
    "hello": "world",
    "fruit": "apple"
}

2. fastapi + nacos服務(wù)注冊

1.安裝pip依賴

[root@bigdata001 ~]#
[root@bigdata001 ~]# pip install fastapi
[root@bigdata001 ~]#
[root@bigdata001 ~]# pip install uvicorn
[root@bigdata001 ~]#
[root@bigdata001 ~]# pip3 install nacos-sdk-python
[root@bigdata001 ~]#

2.router模塊程序如下:

from typing import Optional
from fastapi import APIRouter, Query, Path
fastapi_router=APIRouter()
@fastapi_router.get(path="/")
async def read_root():
    return {"Hello": "World"}
@fastapi_router.get(path = "/items/{my_item_id}",
                    summary='路徑測試',
                    description='路徑測試',
                    tags=['測試模塊'],
                    response_description='{"my_item_id": my_item_id, "q": q}')
async def read_item(my_item_id: int=Path(None, description="我的item id"),
                    q: Optional[str] = Query(None, description="查詢參數(shù)")):
    return {"my_item_id": my_item_id, "q": q}

3.app模塊程序如下:

import nacos
from fastapi import FastAPI
import fastapi_router
def register_server_to_nacos():
    nacos_server_addresses = '192.168.8.246:8848'
    nacos_namespace = 'public'
    nacos_user = 'xxxxxx'
    nacos_password = '123456'
    nacos_cluster_name = 'DEFAULT'
    nacos_group_name = 'DEFAULT_GROUP'
    nacos_project_service_name = 'data-quality-system'
    nacos_project_service_ip = '192.168.8.111'
    nacos_project_service_port = 6060
    
    client = nacos.NacosClient(nacos_server_addresses,
                               namespace=nacos_namespace,
                               username=nacos_user,
                               password=nacos_password)
    client.add_naming_instance(nacos_project_service_name,
                               nacos_project_service_ip,
                               nacos_project_service_port,
                               cluster_name = nacos_cluster_name,
                               weight = 1,
                               metadata = None,
                               enable = True,
                               healthy = True,
                               ephemeral = False,
                               group_name = nacos_group_name)
    client.send_heartbeat(nacos_project_service_name,
                          nacos_project_service_ip,
                          nacos_project_service_port,
                          cluster_name=nacos_cluster_name,
                          weight=1,
                          metadata=None,
                          ephemeral=False,
                          group_name=nacos_group_name)
app = FastAPI(title='my_fastapi_docs',description='my_fastapi_docs')
app.include_router(router=fastapi_router.fastapi_router)
if __name__ == '__main__':
	register_server_to_nacos()
	
    import uvicorn
    uvicorn.run(app=app, host="0.0.0.0",port=8080, workers=1)

4.請求URL: http://192.168.43.50:8080/items/6?q=fastapi

5.查看Web頁面返回結(jié)果如下:

{"my_item_id":6,"q":"fastapi"}

查看fastapi docs路徑:http://192.168.43.50:8080/docs,結(jié)果如下:

fastapi doc

tag部分

response

查看nacos頁面如下:

nacos服務(wù)

服務(wù)詳情

2.1 post

post代碼片段如下:

from pydantic import BaseModel

class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

@fastapi_router.post("/items/")
async def create_item(item: Item):
    print(item.dict())
    return item

執(zhí)行requestTest.py

import requests
url = "http://192.168.88.177:6060/items"
data = {
    "name" : "bigdataboy",
    "price": 100,
}
response = requests.post(url=url,json=data)
print(response.json())

post代碼片段和requestTest.py的執(zhí)行結(jié)果都是

{'name': 'bigdataboy', 'description': None, 'price': 100.0, 'tax': None}

2.2 get請求接收list參數(shù)

get代碼片段如下:

from typing import List

@fastapi_router.get(path = "/items/get_list")
async def get_list(id: int = Query(None),
                    names: List[str] = Query(None)
                   ):
    return {"id":id, "names":names}

訪問http://192.168.88.177:8080/items/get_list?id=3&names=test1&names=test2,得到的結(jié)果如下:

get list的結(jié)果

2.3 請求URL進行文件下載

get代碼片段如下:

from starlette.responses import FileResponse
@fastapi_router.get(path = "/items/downloadFile")
async def downloadFile():
    return FileResponse('C:\\Users\\dell\\Desktop\\test.txt', filename='test.txt')

訪問http://192.168.88.177:8080/items/downloadFile,得到的結(jié)果如下:

下載文件

2.4 獲取Request Headers的Authorization,并使用JWT解析

使用瀏覽器F12查看的Authorization如下:

Authorization

以上URL的請求是公司的前端向后端請求數(shù)據(jù),只是記錄下來,并自己并沒有做模擬測試

jwt的安裝

from starlette.responses import FileResponse

@fastapi_router.get(path = "/items/downloadFile")
async def downloadFile():
    return FileResponse('C:\\Users\\dell\\Desktop\\test.txt', filename='test.txt')

demo如下:

from fastapi import Request
import jwt
@fastapi_router.get(path = "/items/get_authorization")
async def get_authorization(request:Request,
                       name: str):
                       
    authorization = request.headers.get('authorization')
    token = authorization[7:]
    token_dict = jwt.decode(token, options={"verify_signature": False})
	return token_dict

訪問http://192.168.88.177:8080/items/get_authorization?name=zhang_san,得到的結(jié)果如下:

{
'key1': value1, 
'key2': 'value2'
}

到此這篇關(guān)于Python進行Restful API開發(fā)實例的文章就介紹到這了,更多相關(guān)Python Restful API開發(fā)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python辦公自動化之Excel介紹

    Python辦公自動化之Excel介紹

    大家好,本篇文章主要講的是Python辦公自動化之Excel介紹,感興趣的同學(xué)趕快來看一看吧,對你有幫助的話記得收藏一下,方便下次瀏覽
    2021-12-12
  • Python利用operator模塊實現(xiàn)對象的多級排序詳解

    Python利用operator模塊實現(xiàn)對象的多級排序詳解

    python中的operator模塊提供了一系列的函數(shù)操作。下面這篇文章主要給大家介紹了在Python中利用operator模塊實現(xiàn)對象的多級排序的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。
    2017-05-05
  • 使用Python的開發(fā)框架Brownie部署以太坊智能合約

    使用Python的開發(fā)框架Brownie部署以太坊智能合約

    在本文中,我們將使用Python部署智能合約。這篇文章可能是您走向智能合約和區(qū)塊鏈開發(fā)的橋梁!
    2021-05-05
  • Python post請求實現(xiàn)代碼實例

    Python post請求實現(xiàn)代碼實例

    這篇文章主要介紹了Python post請求實現(xiàn)代碼實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-02-02
  • Python3控制路由器——使用requests重啟極路由.py

    Python3控制路由器——使用requests重啟極路由.py

    通過本文給大家介紹Python3控制路由器——使用requests重啟極路由.py的相關(guān)知識,代碼寫了相應(yīng)的注釋,以后再寫成可以方便調(diào)用的模塊,感興趣的朋友一起學(xué)習(xí)吧
    2016-05-05
  • python解析json實例方法

    python解析json實例方法

    這篇文章主要介紹了python解析json數(shù)據(jù)的小實例,代碼簡單實用,大家參考使用吧
    2013-11-11
  • 詳解Python中使用base64模塊來處理base64編碼的方法

    詳解Python中使用base64模塊來處理base64編碼的方法

    8bit的bytecode經(jīng)常會被用base64編碼格式保存,Python中自帶base64模塊對base64提供支持,這里我們就來詳解Python中使用base64模塊來處理base64編碼的方法,需要的朋友可以參考下
    2016-07-07
  • python url 參數(shù)修改方法

    python url 參數(shù)修改方法

    今天小編就為大家分享一篇python url 參數(shù)修改方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-12-12
  • 最近Python有點火? 給你7個學(xué)習(xí)它的理由!

    最近Python有點火? 給你7個學(xué)習(xí)它的理由!

    最近Python有點火?這篇文章主要為大家分享了7個你現(xiàn)在就該學(xué)習(xí)Python的理由,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • Django中使用CORS實現(xiàn)跨域請求過程解析

    Django中使用CORS實現(xiàn)跨域請求過程解析

    這篇文章主要介紹了Django中使用CORS實現(xiàn)跨域請求過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2019-08-08

最新評論