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

Posted 逍遥小天狼

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了饮冰三年-人工智能-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

# 导包
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()
View Code2.0

# 导包
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内容

# 导包
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\'404\']
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

2:一个简单的django案例

  Django的下载与安装

  

  如何检验是否安装成功?

  

  2.1 创建django项目的两种方法  

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

方式2:通过Pycharm创建

创建成功

 

大致分为三步

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

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

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

通过命令行启动django。

python manage.py runserver 8091

 如何引用js

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

b:在setting文件中配置

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

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("2018");
Views.py

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

例3:给分组命名

urls中的配置 

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

views视图中的代码

return HttpResponse(year+"-"+month)

 

例四:注册小练习
<!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="1">读书
            <input type="checkbox" name="hobby" value="2">写字
            <input type="checkbox" name="hobby" value="3">看报
    </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

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

效果图

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

 URL分发

 

 效果:

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方法

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-{{}}和万能的.

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>
过滤器

 

 5.3 标签(tag)的使用

5.3.1 if 和for