day64

# 复习

```python
1 web应用
    -通过浏览器访问的服务
    -cs/bs
    -基于socket
2 Http协议
    -http协议版本,0.9   1.1   2.x  3.x  有什么异同
    -请求头和响应头中的key-value
    -请求协议
        -请求首行:请求方式,地址,协议和版本
        -请求头
        -请求体
    -响应协议
        -响应首行:协议版本,状态码,状态
        -响应头
        -响应体:html,css,js
    -特点
        -基于socket
        -基于请求响应
        -无状态无连接
    -url:统一资源定位符
        
3 web框架
    -wsgiref(socket的封装)自己写了一个web框架
    -django,flask:同步框架  ,tornado,sanic,fastapi:异步框架
    -其他socket服务端(遵循WSGI协议)
        -wsgiref,uwsgi(c语言写的),tornado,gunicorn(python写的)
        -uwsgi+django
        -gunicorn+flask
4 django
    -安装(虚拟环境),创建项目,创建app
    -配路由,写视图函数,modeles
    -静态文件配置
       -路由配置
        -url函数,re_path函数,path函数,四个参数
        -有名,无名分组
        -路径后是否加/
        -路由分发 include
        -反向解析(通过别名拿到路径)
        -名称空间
        -2.x的转换器
        -自定义转化器
5 视图层
    -request对象
        -请求方方法
        -get请求参数,地址栏中的参数
        -post请求参数,请求体中的参数(name=lqz&password=123),有的格式取不出来
        -http://127.0.0.1:8000/login/?name=lqz  向这个地址发送post请求
    -response对象
        -三件套
8 模型层models.py
    -可以创建表,可以删除表,可以新增字段,删除字段(不能创建数据库)
    -默认使用sqlite(如果使用mysql)
    -写类,写字段
        -数据库迁移,两条命令
9 模板层
    -{{变量}}
   
10 请求生命周期,mtv和mvc



 web微信如何做的?(服务端主动向客户端推送消息)
    -轮询
    -长轮询
     -websocket:主动推送消息,应用层协议
```



# 今日内容

## 1 视图层之请求对象

```python
def index(request):
    '''
    request:django封装的对象,它的类是WSGIRequest,它里面包含了所有http请求的东西
    '''
    print(request)
    print(type(request))
    # from django.core.handlers.wsgi import WSGIRequest
    #######################1 
    print(request.method)
    print(request.GET)
    print(request.POST)

    ########################2  path,get_full_path,META,FIELS,body
    # 自定制请求头
    # 默认编码方式urlencoded,上传文件使用的编码方式是form-data,
    print(request.is_ajax()) # 是不是ajax请求
    print(request.path)      # 请求路径
    print(request.get_full_path()) # 请求的全路径,带数据

    # print(request.body)      # 请求体,二进制,如果传文件,这个报错
    '''

    <form action="/index/" method="post" enctype="multipart/form-data">
     action指定表单中的数据提交到哪里,method为请求方法,enctype为编码方式

    使用form表单,默认情况下数据被转成name=lqz&password=123放到请求体中
    request.POST其实是从body中取出bytes格式的,转成了字典
    request.GET其实是把路径中?后面的部分拆出来,转成了字典
    '''
    print(request.encoding)  # 客户端向服务端传递时,使用的编码方法

    print(request.META)    # 重点,字典,包含:发出请求的用户的ip地址,请求头中数据,用户自定制请求头的数据
    '''
    把请求头的key值部分统一加HTTP_  ,并且全部转成大写
      例:在网页中检查结果为user-agent,那么request.META中就是                                                                                                                HTTP_USER_AGENTuser-agenuser-agentt:user-agent:
    '''
    print(request.META['REMOTE_ADDR'])  # 客户端的ip地址
    print(request.FILES)  # 客户端上传的文件



    ########################3 暂时不用关注
    print(request.COOKIES) # 空字典
    print(request.session) # session对象
    print(request.user)    # 匿名用户
    return HttpResponse('ok')
```



## 2 视图层之响应对象

```python
### 重点:JsonResponse的使用(看源码)

def index(request):
    # 三件套
    # return HttpResponse('ok')
    # return render(request,'index.html',context={'name':'lqz','age':18})
    # return redirect('/home') # 重定向自己的地址,重定向第三方地址,经常跟反向解析一起使用

    # 向客户端返回json格式数据
    # import json
    # res=json.dumps({'name':'刘清政','age':18},ensure_ascii=False)
    # return HttpResponse(res)
    # django内置提供的JsonResponse
    # 本质还是HttpResponse
    
    from django.http import JsonResponse
    # ensure_ascii
    # return JsonResponse({'name':'刘清政','age':18},json_dumps_params={'ensure_ascii':False})
    # safe,转换除字典以外的格式,需要safe=False
    return JsonResponse([11,12,13,'lqz',[1,2,3],{'name':'lqz','age':19}],safe=False)
```



## 3 cbv和fbv

```python
# CBV基于类的视图(Class base view)和FBV基于函数的视图(Function base view)
# 之前学的全是FBV,写的是视图函数

# 写视图类(还是写在views.py中)
## 第一步,写一个类,继承View
from django.views import View

class Index(View):
    def get(self, request):  # 当url匹配成功,get请求,会执行它
        return HttpResponse('ok')

    def post(self,request):
        return HttpResponse('post')
    
## 第二步:配置路由
path('index/', views.Index.as_view())   
     # 基于类的视图,路由配置:类名.as_view()


# 前期,全是FBV,后期,drf全是CBV




```



## 4 文件上传

```python
## html注意编码方式
<form action="/index/" method="post" enctype="multipart/form-data">

    <p>用户名:<input type="text" name="name"></p>
    <p>密码:<input type="password" name="password"></p>
    <p><input type="file" name="myfile"></p>
    <p><input type="submit" value="提交"></p>
</form>

# views.py
def index(request):
    file=request.FILES.get('myfile')
    # 打开一个空文件,写入
    with open(file.name,'wb') as f:
        for line in file.chunks():
            f.write(line)
    return HttpResponse('文件上传成功')
```





## 6 postman软件

模拟发送http请求(控制请求路径,请求方式,请求头,请求体)

![image-20201009115049146](.\django-day63.assets\image-20201009115049146.png)


## 7 form表单,提交地址

```python
# action
#1 不写,默认向当前地址发送请求
#2 /index/,向当前域(http://127.0.0.1:8000/)的/index/发送请求
#3 http://127.0.0.1:8000/index/,向该地址发送请求(可以向第三方服务发送请求)

# method
# 1 post:发送post请求(默认编码情况下:以key=value&key=value的形式拼到请求体中)
# 2 get:发送get请求(以key=value&key=value的形式拼到路径中)
<form action="/index/" method="post">

    <p>用户名:<input type="text" name="name"></p>
    <p>密码:<input type="text" name="password"></p>
    <p><input type="submit" value="提交"></p>
</form>
```



## 8 Pycharm的自动提示

```python
from django.core.handlers.wsgi import WSGIRequest
# pycharm的自动提示
request=request  # type: WSGIRequest
```



# 作业

1 写一个项目,统计用户访问日志,记录用户的ip地址和访问时间,访问地址,存到mysql数据库

 

posted @ 2020-10-09 21:32  板鸭没有腿  阅读(114)  评论(0)    收藏  举报