这个博客分享一个fastapi的模版,并提供使用http/python访问的示例程序
下面是一个示例:
/example_connect
# !/usr/bin Python
# coding=utf-8
import os
import sys
import warnings
warnings.filterwarnings('ignore')
sys.path.append(os.pardir)
from fastapi import FastAPI, Query
import uvicorn
app = FastAPI()
@app.get("/example_connect")
async def check_web(name=Query(None), value=Query(None)):
# 示例
return {
"name": name,
"value": value
}
if __name__ == "__main__":
from pathlib import Path
uvicorn.run(f"{Path(__file__).stem}:app",
host="127.0.0.1", # IP
port=18866, # 端口
workers=1) # 启动进程
在浏览器中访问:http://127.0.0.1:18866/example_connect?name=a
得到如下返回结果:
Python使用requests
进行请求,同时添加params
作为参数
# !/usr/bin Python
# coding=utf-8
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Safari/537.36",
}
url = "http://127.0.0.1:18866/example_connect" # 请求URL
params = {"name": "a"} # 参数
response = requests.get(url=url, params=params, headers=headers)
result_dict = eval(response.text.replace("null", "None")) # 获取结果并转为dict
print(result_dict)