Skip to content
  •  
  •  
  •  
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
__pycache__/
*.py[cod]

.idea/
7 changes: 4 additions & 3 deletions chapter01/asyncio/contrast_async_other.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ async def wrapper(*args, **kwargs):
async def request_async():
# 异步请求函数
async with aiohttp.ClientSession() as session:
async with session.get('https://www.baidu.com') as resp:
async with session.get("https://www.baidu.com") as resp:
pass


Expand All @@ -44,9 +44,10 @@ def main():


import os
if __name__ == '__main__':

if __name__ == "__main__":
# 需要注意需要在此处设置才可以运行
if os.name == 'nt':
if os.name == "nt":
# 在Windows系统中设置事件循环策略,解决 "Event loop is closed" 错误
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
main()
Expand Down
10 changes: 7 additions & 3 deletions chapter01/asyncio/contrast_sync.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import requests
import time


def take_up_time(func):
def wrapper(*args, **kwargs):
print("开始执行---->")
Expand All @@ -9,17 +10,20 @@ def wrapper(*args, **kwargs):
using = (time.time() - now) * 1000
print(f"结束执行,消耗时间为:{using}ms")
return result

return wrapper


def request_sync(url):
response = requests.get(url)
return response


@take_up_time
def run():
for i in range(0, 50):
request_sync('https://www.baidu.com')
request_sync("https://www.baidu.com")


if __name__ == '__main__':
run()
if __name__ == "__main__":
run()
10 changes: 6 additions & 4 deletions chapter01/asyncio/cotrast_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,19 @@ def wrapper(*args, **kwargs):

async def request_async():
async with aiohttp.ClientSession() as session:
async with session.get('https://www.baidu.com') as resp:
async with session.get("https://www.baidu.com") as resp:
pass


@take_up_time
def run():
tasks = [asyncio.ensure_future(request_async()) for x in range(0, 49)]
loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
tasks = [asyncio.ensure_future(request_async(), loop=loop) for x in range(0, 49)]
# loop = asyncio.get_event_loop()
tasks = asyncio.gather(*tasks)
loop.run_until_complete(tasks)


if __name__ == '__main__':
if __name__ == "__main__":
run()
28 changes: 15 additions & 13 deletions chapter02/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,37 +7,39 @@
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles

app = FastAPI(title="学习Fastapi框架文档",
description="以下是关于相Fastapi框架文档介绍和描述",
version="0.0.1",debug=True)

app = FastAPI(
title="学习Fastapi框架文档",
description="以下是关于相Fastapi框架文档介绍和描述",
version="0.0.1",
debug=True,
)


templates = Jinja2Templates(directory=f"{pathlib.Path.cwd()}/templates/")
staticfiles = StaticFiles(directory=f"{pathlib.Path.cwd()}/static/")
app.mount("/static", staticfiles, name="static")


@app.get('/', response_class=HTMLResponse)
@app.get('/index', response_class=HTMLResponse)
@app.post('/index', response_class=HTMLResponse)
@app.get("/", response_class=HTMLResponse)
@app.get("/index", response_class=HTMLResponse)
@app.post("/index", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse("index.html",
{"request": request})
return templates.TemplateResponse("index.html", {"request": request})


def myinex():
return {"Hello": "myinex api"}


app.get("/myindex", tags=["路由注册方式"], summary="路由注册方式说明")(myinex)


@app.route('/loginjig', methods=['GET', 'POST'], name='loginjig')
@app.route("/loginjig", methods=["GET", "POST"], name="loginjig")
def loginjig(req: Request):
return PlainTextResponse('大爷')
return PlainTextResponse("大爷")


if __name__ == '__main__':
if __name__ == "__main__":
import uvicorn

uvicorn.run(app='main:app', host="127.0.0.1", port=65535, reload=True, debug=True)
uvicorn.run(app="main:app", host="127.0.0.1", port=65535, reload=True, debug=True)
Original file line number Diff line number Diff line change
Expand Up @@ -6,35 +6,35 @@

app = FastAPI()


# ============多重URL地址绑定函数============
# =========================================
@app.get('/', response_class=JSONResponse)
@app.get('/index', response_class=JSONResponse)
@app.post('/index', response_class=JSONResponse)
@app.get("/app/hello", tags=['app实例对象注册接口-示例'])
@app.get("/", response_class=JSONResponse)
@app.get("/index", response_class=JSONResponse)
@app.post("/index", response_class=JSONResponse)
@app.get("/app/hello", tags=["app实例对象注册接口-示例"])
def app_hello():
return {"Hello": "app api"}


# ============同一个URL动态和静态路由==========
# =========================================
# 动态路由
@app.get('/user/{userid}')
@app.get("/user/{userid}")
async def login(userid: str):
return {"Hello": "dynamic"}


# 静态路由
@app.get('/user/userid')
@app.get("/user/userid")
async def login():
return {"Hello": "static"}




if __name__ == "__main__":
import uvicorn
import os

app_modeel_name = os.path.basename(__file__).replace(".py", "")
print(app_modeel_name)
uvicorn.run(f"{app_modeel_name}:app", host='127.0.0.1', reload=True)
app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
31 changes: 31 additions & 0 deletions chapter03/3_2_2_static_dynamic/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#!/usr/bin/evn python
# -*- coding: utf-8 -*-

from fastapi import FastAPI
from fastapi import APIRouter
from starlette.responses import JSONResponse

app = FastAPI(routes=None)


# ============一个URL配置多个HTTP请求方法==========
# =========================================
@app.api_route(path="/index", methods=["GET", "POST"])
async def index():
return {"index": "index"}


async def index2():
return JSONResponse({"index": "index2"})


app.add_api_route(path="/index2", endpoint=index2, methods=["GET", "POST"])


if __name__ == "__main__":
import uvicorn
import os

app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
44 changes: 44 additions & 0 deletions chapter03/3_2_3_demo_more_routers/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
from fastapi import FastAPI
from fastapi import APIRouter

app = FastAPI(routes=None)

router_user = APIRouter(prefix="/user", tags=["用户模块"])
router_pay = APIRouter(prefix="/pay", tags=["支付模块"])


@router_user.get("/{user}/login")
def user_login(user: str):
return {"user": user, "login": f"{user} login success!"}


@router_pay.post("/{user}/pay")
def user_pay(user: str):
return {"user": user, "pay": f"{user} pay success!"}


app.include_router(router_user)
app.include_router(router_pay)


@router_user.api_route("/{user}/api/login", methods=["GET", "POST"])
def user_api_route_login(user):
return {"ok": f"用户 {user} api登入成功!"}


def add_user_api_route_login():
return {"ok": "登入成功!"}


router_user.add_api_route(
"/user/add/api/login", methods=["GET", "POST"], endpoint=add_user_api_route_login
)
app.include_router(router_user)

if __name__ == "__main__":
import uvicorn
import os

app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,28 @@
import threading
import time
import asyncio

app = FastAPI(routes=None)


@app.get(path="/async")
async def asyncdef():
await asyncio.sleep(10)
await asyncio.sleep(3)
print("当前协程运行的线程ID:", threading.current_thread().ident)
return {"index": "async"}


@app.get(path="/sync")
def syncdef():
time.sleep(10)
print("当前普通函数运行的线程ID:",threading.current_thread().ident)
time.sleep(3)
print("当前普通函数运行的线程ID:", threading.current_thread().ident)
return {"index": "sync"}




if __name__ == "__main__":
import uvicorn
import os

app_modeel_name = os.path.basename(__file__).replace(".py", "")
print(app_modeel_name)
uvicorn.run(f"{app_modeel_name}:app", host='127.0.0.1', reload=True)
app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
32 changes: 32 additions & 0 deletions chapter03/3_4_mount_app/fastapiapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/evn python
# -*- coding: utf-8 -*-

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI(title="主应用", description="我是主应用文档的描述", version="v1.0.0")


@app.get("/index", summary="首页")
async def index():
return JSONResponse({"index": "我是属于主应用的接口!"})


subapp = FastAPI(title="子应用", description="我是子应用文档的描述", version="v1.0.0")


@subapp.get("/index", summary="首页")
async def index():
return JSONResponse({"index": "我是属于子应用的接口!"})


app.mount(path="/subapp", app=subapp, name="subapp")


if __name__ == "__main__":
import uvicorn
import os

app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
32 changes: 32 additions & 0 deletions chapter03/3_4_mount_app/flaskapp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#!/usr/bin/evn python
# -*- coding: utf-8 -*-

from fastapi import FastAPI
from fastapi.responses import JSONResponse

app = FastAPI(title="主应用", description="我是主应用文档的描述", version="v1.0.0")


@app.get("/index", summary="首页")
async def index():
return JSONResponse({"index": "我是属于主应用的接口!"})


subapp = FastAPI(title="子应用", description="我是子应用文档的描述", version="v1.0.0")


@subapp.get("/index", summary="首页")
async def index():
return JSONResponse({"index": "我是属于子应用的接口!"})


app.mount(path="/subapp", app=subapp, name="subapp")


if __name__ == "__main__":
import uvicorn
import os

app_model_name = os.path.basename(__file__).replace(".py", "")
print(app_model_name)
uvicorn.run(f"{app_model_name}:app", host="127.0.0.1", reload=True)
Loading