饮冰三年-人工智能-Python-22 Python初识Django

时间:2023-03-09 04:04:22
饮冰三年-人工智能-Python-22 Python初识Django

1:一个简单的web框架

# 导包
from wsgiref.simple_server import make_server
#自定义个处理函数
def application(environ,start_response):
start_response("200 OK",[('Content-Type','text/html')])
return [b'<h1>Hello,web!</h1>'] httpd = make_server('',8091,application)
print('Serving HTTP on port 8091....')
httpd.serve_forever()

HelloWorld

饮冰三年-人工智能-Python-22 Python初识Django

# 导包
from wsgiref.simple_server import make_server
#自定义个处理函数
def application(environ,start_response):
# 获取路径
path = environ["PATH_INFO"]
start_response("200 OK",[('Content-Type','text/html')])
if path=="/yang":
return [b'<h1>Hello,yang!</h1>']
elif path=="/Aaron":
return [b'<h1>Hello,aaron!</h1>']
else:
return [b'<h1>404!</h1>'] httpd = make_server('',8091,application)
print('Serving HTTP on port 8091....')
httpd.serve_forever()

2.0

饮冰三年-人工智能-Python-22 Python初识Django

# 导包
from wsgiref.simple_server import make_server def yang():
f=open("yang.html","rb")
data=f.read()
return data
def aaron():
f=open("aaron.html","rb")
data=f.read()
return data
#自定义个处理函数
def application(environ,start_response):
# 获取路径
path = environ["PATH_INFO"]
start_response("200 OK",[('Content-Type','text/html')])
if path=="/yang":
return [yang()]
elif path=="/Aaron":
return [aaron()]
else:
return [b'<h1>404!</h1>'] httpd = make_server('',8091,application)
print('Serving HTTP on port 8091....')
httpd.serve_forever()

调用HTML内容

饮冰三年-人工智能-Python-22 Python初识Django

# 导包
import time
from wsgiref.simple_server import make_server def region(req):
pass;
def login(req):
print(req["QUERY_STRING"])
f=open("login.html",'rb')
data=f.read();
return data;
def yang(req):
f=open("yang.html","rb")
data=f.read()
return data
def aaron(req):
f=open("aaron.html","rb")
data=f.read()
return data
def show_time(req):
times=time.ctime()
# 方法一:通过模板使用
# con=("<h1>time:%s</h1>" %str(times)).encode("utf8")
# return con
# 方法二:字符串替换
f = open("show_time.html", "rb")
data = f.read()
data=data.decode("utf8")
data =data.replace("{{time}}",str(times))
return data.encode("utf8")
# 定义路由
def router():
url_patterns=[
("/login",login),
("/region", region),
("/yang", yang),
("/aaron", aaron),
("/show_time",show_time),
] return url_patterns
#自定义个处理函数
def application(environ,start_response):
# 获取路径
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 func:
return [func(environ)]
else:
return [b'']
httpd = make_server('',8091,application)
print('Serving HTTP on port 8091....')
httpd.serve_forever()

模拟路由

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<h1>时间:{{time}}}</h1>
</body>
</html>

show_time.html

饮冰三年-人工智能-Python-22 Python初识Django

2:一个简单的django案例

  Django的下载与安装

  饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

  如何检验是否安装成功?

  饮冰三年-人工智能-Python-22 Python初识Django

  2.1 创建django项目的两种方法  

--创建Django项目
django-admin startproject mysite --创建应用
python manage.py startapp blog

通过命令创建

饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

方式2:通过Pycharm创建

饮冰三年-人工智能-Python-22 Python初识Django

创建成功

饮冰三年-人工智能-Python-22 Python初识Django

大致分为三步

a:修改urls.py 类似控制器,把想要展示的内容通过地址配置一下

饮冰三年-人工智能-Python-22 Python初识Django

b:在views中设置具体的逻辑

饮冰三年-人工智能-Python-22 Python初识Django

c:在templates中设置要显示的页面内容

饮冰三年-人工智能-Python-22 Python初识Django

通过命令行启动django。

python manage.py runserver 8091

饮冰三年-人工智能-Python-22 Python初识Django

如何引用js

a:添加static文件,并把js放置到该文件下

饮冰三年-人工智能-Python-22 Python初识Django

b:在setting文件中配置

饮冰三年-人工智能-Python-22 Python初识Django

c:在对应的文件中做引用

饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

3:URL配置(URLconf):又叫做路由系统,其本质是提供路径和视图函数之间的调用映射表。

格式:

  urlpatterns=[

    url(正在表达式,views视图函数,参数,别名)

  ]

例1:匹配 XXX/articles/年份(只能匹配4位数字)

from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show_time/',views.show_time),
url(r'^articles/[0-9]{4}/$', views.year_archive), ]

urls.py--1.0

from django.shortcuts import render,HttpResponse
import time
def show_time(request):
# return HttpResponse("Hello")
return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request):
return HttpResponse("");

Views.py

饮冰三年-人工智能-Python-22 Python初识Django

例2:如何获取到地址栏中的年份(通过路由添加()匹配)

饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

例3:给分组命名

urls中的配置

url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$', views.year_archive),

views视图中的代码

return HttpResponse(year+"-"+month)

饮冰三年-人工智能-Python-22 Python初识Django

例四:注册小练习
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="" method="post">
<p>姓名 <input type="text" name="name"></p>
<p>年龄 <input type="text" name="age"></p>
<p>爱好 <input type="checkbox" name="hobby" value="">读书
<input type="checkbox" name="hobby" value="">写字
<input type="checkbox" name="hobby" value="">看报
</p>
<p><input type="submit"></p>
</form>
</body>
</html>

Register.html

from django.shortcuts import render,HttpResponse
import time
def show_time(request):
# return HttpResponse("Hello")
return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request,month,year):
return HttpResponse(year+"-"+month) def Register(request):
if request.method=="POST":
con="Hello,%s,你的年龄是%s"%(request.POST.get("name"),request.POST.get("age"))
return HttpResponse(con)
return render(request,"Register.html")

Views.py

"""django01 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('show_time/',views.show_time),
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$', views.year_archive),
url(r'^Register/', views.Register), ]

urls.py

注意:需要把这句代码给注释掉

饮冰三年-人工智能-Python-22 Python初识Django

效果图

饮冰三年-人工智能-Python-22 Python初识Django饮冰三年-人工智能-Python-22 Python初识Django

在url中给地址设置一个别名,这样后期Register名称的修改将不影响系统中其他调用的功能

饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

URL分发

饮冰三年-人工智能-Python-22 Python初识Django

饮冰三年-人工智能-Python-22 Python初识Django

效果:

饮冰三年-人工智能-Python-22 Python初识Django

4:视图(Views)

http请求中产生两个核心对象:

http请求:HttpRequest对象

http响应:HttpResponse对象

4.1 HttpRequest对象的属性和方法:

4.2 HttpResponse对象:

页面渲染:         render()(推荐)<br>                 render_to_response(),

页面跳转:         redirect("路径")
locals():    可以直接将函数中所有的变量传给模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
4.1 HttpRequest对象的属性和方法: <br/>
姓名: {{ name}} <br/>
年龄:{{ age }} <br/>
路径:{{ reqPath }} <br/>
全路径:{{ reqFullPath }} <br/>
请求方法:{{ request.method }} <br/>
4.2 HttpResponse对象: <br/>
页面渲染:render()(推荐)<br>
页面渲染:render_to_response <br/> render_to_response(),
页面跳转: redirect("路径")
locals(): 可以直接将函数中所有的变量传给模板
</body>
</html>

新增一个Welcome的页面

from django.contrib import admin
from django.urls import path
from django.conf.urls import url,include
from blog import views
urlpatterns = [
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})$', views.year_archive),
url(r'^Register2/', views.Register,name='reg'),
url(r'^Welcome/', views.Welcome, name='we'),
]

配置url信息

from django.shortcuts import render,HttpResponse,render_to_response,redirect
import time
def show_time(request):
# return HttpResponse("Hello")
return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request,month,year):
return HttpResponse(year+"-"+month) def Register(request):
if request.method=="POST":
# name = request.POST.get("name")
# age =request.POST.get("age")
# reqPath= request.path
# reqFullPath = request.get_full_path()
# return redirect("../Welcome",locals())
Welcome(request)
return redirect("../Welcome", locals())
return render(request, "Register2.html") def Welcome(request):
name = "张三"
age = "李四"
reqPath = request.path
reqFullPath = request.get_full_path()
return render_to_response("Welcome.html",locals())

添加View方法

饮冰三年-人工智能-Python-22 Python初识Django

5:模板(HTML+逻辑控制代码)

5.1 变量

from django.shortcuts import render,HttpResponse,render_to_response,redirect
import time
def show_time(request):
# return HttpResponse("Hello")
return render(request,"index.html",{"time":time.ctime()})
# Create your views here.
def year_archive(request,month,year):
return HttpResponse(year+"-"+month) def Register(request):
if request.method=="POST":
# name = request.POST.get("name")
# age =request.POST.get("age")
# reqPath= request.path
# reqFullPath = request.get_full_path()
# return redirect("../Welcome",locals())
Welcome(request)
return redirect("../Welcome", locals())
return render(request, "Register2.html") def Welcome(request):
name = ['zhangsan','lisi']
age = "李四1"
reqPath = request.path
reqFullPath = request.get_full_path()
return render_to_response("Welcome.html",locals())
class CVariable():
def __init__(self,name,age):
self.name=name
self.age = age
def Variable(request):
test1='字符串变量直接显示'
test2=['apples', 'bananas', 'carrots']
test3={"name":"字典名称","age":12}
test4=CVariable("张三",12)
return render(request,"Variable.html",locals())

def Variable(request):

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load staticfiles %}
</head>
<body>
<p>字符串变量:{{ test1 }}</p>
<p>数组变量:{{ test2.1 }}</p>
<p>字典变量:{{ test3.name }}</p>
<p>类变量:{{ test4.age }}</p>
<p>转大写:{{ test2.1.upper }}</p>
</body>
</html>

HTML-{{}}和万能的.

饮冰三年-人工智能-Python-22 Python初识Django

5.2 过滤器

语法格式:      {{obj|filter:param}}

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load staticfiles %}
</head>
<body>
<p>字符串变量:{{ test1 }}</p>
<p>数组变量:{{ test2.1 }}</p>
<p>字典变量:{{ test3.name }}</p>
<p>类变量:{{ test4.age }}</p>
<p>转大写:{{ test2.1.upper }}</p>
<p>---------我是过滤器的分割线-----------</p>
<p>过滤器转大写:{{ test2.1|upper }}</p>
<p>过滤器+3:{{ test4.age|add:3 }}</p>
<p>过滤器移除a字符:{{ test2.1|cut:'a' }}</p>
<p>过滤器日期格式化:{{ test5|date:'Y-m-d' }}</p>
<p>过滤器判断是否为空:{{ test6|default:'空的' }}</p>
<p>过滤器判断是否None:{{ test7|default_if_none:"None值" }}</p>
<p>过滤器链接:{{ test8|safe }}</p>
<p>过滤器链接2:
{% autoescape off %}
{{ test8 }}
{% endautoescape%}
</p>
<p>过滤器计算长度:{{ test2|length }}</p>
<p>过滤器取第一个元素:{{ test2|first }}</p>
</body>
</html>

过滤器

饮冰三年-人工智能-Python-22 Python初识Django

5.3 标签(tag)的使用

5.3.1 if 和for

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load staticfiles %}
</head>
<body>
<p>字符串变量:{{ test1 }}</p>
<p>数组变量:{{ test2.1 }}</p>
<p>字典变量:{{ test3.name }}</p>
<p>类变量:{{ test4.age }}</p>
<p>转大写:{{ test2.1.upper }}</p>
<p>---------我是过滤器的分割线-----------</p>
<p>过滤器转大写:{{ test2.1|upper }}</p>
<p>过滤器+3:{{ test4.age|add:3 }}</p>
<p>过滤器移除a字符:{{ test2.1|cut:'a' }}</p>
<p>过滤器日期格式化:{{ test5|date:'Y-m-d' }}</p>
<p>过滤器判断是否为空:{{ test6|default:'空的' }}</p>
<p>过滤器判断是否None:{{ test7|default_if_none:"None值" }}</p>
<p>过滤器链接:{{ test8|safe }}</p>
<p>过滤器链接2:
{% autoescape off %}
{{ test8 }}
{% endautoescape%}
</p>
<p>过滤器计算长度:{{ test2|length }}</p>
<p>过滤器取第一个元素:{{ test2|first }}</p>
<p>---------我是标签tag的分割线-----------</p>
---if 判断---<br/>
{% if test4.age > 20 %}
{% if test4.age > 50 %}
<p>年龄在:50以上</p>
{% else %}
<p>年龄在:20-50之间</p>
{% endif %}
{% elif test4.age < 10 %}
<p>年龄在:10以下</p>
{% else %}
<p>年龄在:10-20 之间</p>
{% endif %}
---for 判断---<br/>
{% for item in test2 %}
{% if forloop.first %}
<p style="color: red">序号:{{ forloop.counter }},名称:{{ item }}</p>
{% else %}
<p>序号:{{ forloop.counter }},名称:{{ item }}</p>
{% endif %}
{% endfor %}
注意:<br/>
1,forloop.counter表示循环的次数,它从1开始计数,第一次循环设为1:<br/>
2,forloop.counter0 类似于forloop.counter,但它是从0开始计数,第一次循环设为0<br/>
3,forloop.revcounter<br/>
4,forloop.revcounter0<br/>
5,forloop.first当第一次循环时值为True,在特别情况下很有用:<br/>
---if 判断---<br/> </body>
</html>

饮冰三年-人工智能-Python-22 Python初识Django

5.3.2 {%csrf_token%} 

用于生成csrf_token的标签,用于防治跨站攻击验证。注意如果你在view的index里用的是render_to_response方法,不会生效

其实,这里是会生成一个input标签,和其他表单标签一起提交给后台的。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
{% load staticfiles %}
</head>
<body>
<form action="{% url 'reg' %}" method="post">
<p>姓名 <input type="text" name="name"></p>
<p>年龄 <input type="text" name="age"></p>
<p>爱好 <input type="checkbox" name="hobby" value="">读书
<input type="checkbox" name="hobby" value="">写字
<input type="checkbox" name="hobby" value="">看报
</p>
<p><input type="submit"></p>
{%csrf_token%}
</form>
</body>
</html>

csrf_token

5.3.3 为复杂变量名起别名{% with %}:

 ---with 判断---<br/>
{% with test9test9test9test9test9test9test9 as a %}
{{ a }}
{% endwith %}

with

5.3.4 取消渲染

 ---取消渲染---<br/>
{% verbatim %}
{{adsf}}
{% endverbatim %}

取消渲染

5.3.5 引用路由配置的地址{% url %} 和 加载标签库{% load %}: 

饮冰三年-人工智能-Python-22 Python初识Django

5.4 自定义过滤器

1:首先在app中创建templatetags模块

2:并在templatetags模块下创建.py文件,并设置自定义过滤器方法

# 导包
from django import template
from django.utils.safestring import mark_safe register = template.Library() #regkster的名字是固定的 @register.filter
def filter_multi(v1,v2):
return v1*v2

my_tag.py

3:在文件中引入{% load my_tags%}

饮冰三年-人工智能-Python-22 Python初识Django

效果:、

饮冰三年-人工智能-Python-22 Python初识Django

但是过滤器无法实现两个参数的传递,这时候需要simple_tag

# 导包
from django import template
from django.utils.safestring import mark_safe register = template.Library() #regkster的名字是固定的 @register.filter
def filter_multi(v1,v2):
return v1*v2 @register.simple_tag
def simple_tag_multi(v1,v2,v3):
return v1*v2*v3

my_tags.py

饮冰三年-人工智能-Python-22 Python初识Django