from io import BytesIO
from pathlib import Path
from tempfile import TemporaryDirectory
from wsgiref.util import setup_testing_defaults
import asyncio
import json
import os
import subprocess
import sys
from cli_exercise import check
def protocols():
from harbor.wsgi import application as wsgi
from harbor.asgi import application as asgi
def request_wsgi(path,host):
environ={"PATH_INFO":path,"HTTP_HOST":host,"wsgi.input":BytesIO()}
setup_testing_defaults(environ)
headers=[]
content=wsgi(environ,lambda status,fields:headers.append(status))
try:
body=b"".join(content)
finally:
content.close()
return int(headers[0].split()[0]),body
async def request_asgi():
events=[]
arrived=False
async def receive():
nonlocal arrived
if not arrived:
arrived=True
return {"type":"http.request","body":b"","more_body":False}
await asyncio.Future()
async def send(message):
events.append(message)
await asgi({"type":"http","asgi":{"version":"3.0"},"http_version":"1.1","method":"GET",
"scheme":"http","path":"/catalog/health/","raw_path":b"/catalog/health/",
"root_path":"","query_string":b"","headers":[(b"host",b"localhost")],
"client":("127.0.0.1",4567),"server":("127.0.0.1",80)},receive,send)
return events[0]["status"],json.loads(b"".join(event["body"] for event in events[1:]))
code,data=request_wsgi("/catalog/label/7/","localhost")
allowed=asyncio.run(request_asgi())
unknown=request_wsgi("/catalog/label/7/","evil.invalid")[0]
regex=request_wsgi("/catalog/code/nw/","localhost")
bad=request_wsgi("/catalog/code/AA/","localhost")[0]
return check("Django WSGI, ASGI and host-routing boundaries",
"Invoke WSGI bytes and ASGI events with the project callables and compare invalid hosts and URLs",
["catalog:label with kwargs","async health","evil.invalid","valid and invalid regex"],
[200,{"number":7,"type":"int","section":"coast"},[200,{"runtime":"async view"}],400,200,"nw",404],
[code,json.loads(data),list(allowed),unknown,regex[0],regex[1].decode(),bad])
def media(root):
(root/"sample.txt").write_bytes(b"isolated media bytes")
probe="""import django,json
django.setup()
from django.conf import settings
from django.test import Client
r=Client().get('/media/sample.txt')
content=b''.join(r.streaming_content) if r.streaming else r.content
print(json.dumps([settings.DEBUG,r.status_code,content==b'isolated media bytes']))
"""
actual=[]
for module in ("harbor.dev_settings","harbor.settings"):
child=subprocess.run([sys.executable,"-B","-c",probe],env=dict(os.environ,DJANGO_LAB_MEDIA_ROOT=str(root),
DJANGO_SETTINGS_MODULE=module),capture_output=True,encoding="utf8",timeout=12,check=True)
actual.append(json.loads(child.stdout))
return check("Django development media route is absent under default settings",
"Use two actual Django settings modules to fetch the same temporary media file",
["development","default"],[[True,200,True],[False,404,False]],actual)
if __name__=="__main__":
with TemporaryDirectory(prefix="mbsky-django-blueprint-media-") as work:
print(json.dumps([protocols(),media(Path(work))],ensure_ascii=False))
本例需在 Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录
入口文件:projects/django-blueprint/interface_exercise.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
interface_exercise.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、CPython 3.12.14、Django 5.2.19、SQLite 3.53.1、本机回环与隔离目录。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip
课程关联工程包(登记关联3章) · 含当前章节或实例 · mbskycom202612a165.zip