一、简单的webserver框架
from wsgiref.simple_server import make_server
def login(req): #view函数
print(req["QUERY_STRING"])
return b"welcome!"
def signup(req):
pass
def dongfei(req):
return b"<h1>Hello Dongfei</h1>"
def router(): #路由函数
url_patterns=[
("/login", login),
("/signup", signup),
("/dongfei", dongfei)
]
return url_patterns
def application(environ, start_response):
print("path",environ["PATH_INFO"])
path=environ["PATH_INFO"]
start_response('200 OK', [('Content-Type', 'text/html')]) # 设置请求头
url_patterns = router()
func = None
for item in url_patterns:
if item[0] == path:
func = item[1]
break
if not func:
return [b'404']
return [func(environ)]
# return [b'<h1>Hello World!</h1>'] #响应请求体
httpd = make_server('', 8080, application)
print('Serving HTTP on port 8080...')
httpd.serve_forever()
二、MVC和MTV模型
1、MVC模型
- M:模型,负责业务对象与数据库的对象(ORM)
- C:控制器,接受用户的输入调用模型和视图完成用户请求
- V:视图,指展示的HTML文件
2、MTV模型
- M:模型,负责业务对象与数据库的对象(ORM)
T:模板,HTML模板文件
V:视图函数,view,和MVC模型中的C功能类似
三、Django环境准备
>pip install django
>django-admin startproject mysite01 #创建Django项目
>cd mysite01
mysite01>python manage.py startapp blog #创建app
-─mysite01
│ manage.py
│
├─blog
│ │ admin.py
│ │ apps.py
│ │ models.py
│ │ tests.py
│ │ views.py #视图
│ │ __init__.py
│ │
│ └─migrations
│ __init__.py
│
└─mysite01
│ settings.py #与Django相关的所有的配置信息
│ urls.py #负责路由分发
│ wsgi.py
│ __init__.py
│
└─__pycache__
settings.cpython-36.pyc
__init__.cpython-36.pyc
四、简单Django项目
- urls.py
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show_time', views.show_time) #路由信息
]
- blog/views.py
from django.shortcuts import render,HttpResponse
import time
def show_time(request):
now_time = time.ctime()
return render(request, "index.html", locals())
- templates/index.html
<body>
<h1>Time: {{ now_time }}</h1>
</body>
五、css/js等静态文件的引入
1、第一种引入方式
- setting.py
STATIC_URL = '/static/' #别名
STATICFILES_DIRS=(
os.path.join(BASE_DIR,"static"),
)
- templates/index.html
<body>
<h1>Time: {{ now_time }}</h1>
<script src="/static/jquery-3.4.1.js"></script>
<script>
$("h1").css("color","red")
</script>
</body>
- 创建一个static文件夹,将jquery文件放在此文件夹下
2、第二种引入方式
- templates/index.html
<head>
<meta charset="UTF-8">
{% load staticfiles %} #在此load
<title>Title</title>
</head>
<body>
<h1>Time: {{ now_time }}</h1>
<script src="{% static 'jquery-3.4.1.js' %}"></script> #指定文件
<script>
$("h1").css("color","red")
</script>
</body>
### 六、Url路由配置系统
- 无命名分组
path('article/<int:year>/<int:month>',views.article_year),
- 命名分组
path('hello/<str:name>/', views.printname),
- 别名
path('register', views.register, name="alias_reg") #定义别名
<form action="{% url 'alias_reg' %}"></form> #引用别名
- 路由分发
from django.urls import path,include
urlpatterns = [
path('blog/', include('blog.urls'))
]
from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show_time', views.show_time),
path('article/<int:year>/<int:month>/<str:name>',views.article_year),
path('hello/<str:name>/', views.printname),
path('register', views.register, name="alias_reg")
]
七、View函数
1、request对象
def show_time(request):
print(request.path) #/blog/show_time
print(request.get_full_path()) #/blog/show_time?name=dongfei
now_time = time.ctime()
return render(request, "index.html", locals())
2、HttpResponse对象
from django.shortcuts import render,HttpResponse,render_to_response
import time
def show_time(request):
print(request.path) #/blog/show_time
print(request.get_full_path()) #/blog/show_time?name=dongfei
now_time = time.ctime()
# return render(request, "index.html", locals()) #推荐使用render,locals()将局部变量传给templates
return render_to_response("index.html", locals())
3、redirect对象
from django.shortcuts import render,HttpResponse,render_to_response,redirect
import time
def show_time(request):
return redirect("http://time.tianqi.com/") #跳转