zoukankan      html  css  js  c++  java
  • request response cookie session

    request

    1. url传递参数

    1)参数没有命名, 如:

    users/views

    def weather(request, city, year):
        print(city)
        print(year)
        return HttpResponse('OK')

    users/urls

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        # url(路径, 视图)
        url(r'^weather/([a-z]+)/(d{4})/$', views.weather, name='weather'),
    ]
    

     

    image

    2) 参数命名, 如

    from django.conf.urls import url
    from . import views
    
    urlpatterns = [
        # url(路径, 视图)
        # url(r'^weather/([a-z]+)/(d{4})/$', views.weather, name='weather'),
        url(r'^weather/(?P<city>[a-z]+)/(?P<year>d{4})/$', views.weather),
    ]

    ?P<city>  就是给参数命名为city

    2. django中的querydict对象

    1) 方法get():根据键获取值

    如果键不存在则返回None值,可以设置默认值进行后续处理

    dict.get('键',默认值)
    # 可简写为
    dict['键']

    2) 方法getlist():根据键获取值,值以列表返回,可以获取指定键的所有值

    如果键不存在则返回空列表[],可以设置默认值进行后续处理

    dict.getlist('键',默认值)

    3. 查询字符串Query string

    比如 字符串参数 ?k1=v1&k2=v2 可以通过request.GET属性获取返回QueryDict对象。

    url为

    http://192.168.33.10:8000/users/qs/?a=10&b=20

    views为

    def qs(request):
        a = request.GET.get('a')
        b = request.GET.get('b')
        alist = request.GET.getlist('a')
        print(a)
        print(b)
        print(alist)
        return HttpResponse('OK')

    返回结果为:

    image

    3. 表单数据类型Form Data

    1) 前端发送的数据是表单类型,可以通过request.POST属性获取,返回QueryDict对象

    def get_body(request):
        a = request.POST.get('a')
        b = request.POST.get('b')
        alist = request.POST.getlist('a')
        print(a)
        print(b)
        print(alist)
        return HttpResponse('OK')

    4. 非表单数据类型Non Form Data

    可以通过request.body属性获取最原始的请求体数据,自己按照请求体格式(JSON、XML等)进行解析。request.body返回bytes类型。

    例如要获取请求体中的如下JSON数据

    {"a": 1, "b": 2}
    import json
    
    def get_body_json(request):
        json_str = request.body
        json_str = json_str.decode()  # python3.6 无需执行此步
        req_data = json.loads(json_str)
        print(req_data['a'])
        print(req_data['b'])
        return HttpResponse('OK')

    5. 请求头

    可以通过request.META属性获取请求头headers中的数据,request.META为字典类型

    • CONTENT_LENGTH – The length of the request body (as a string).
    • CONTENT_TYPE – The MIME type of the request body.
    • HTTP_ACCEPT – Acceptable content types for the response.
    • HTTP_ACCEPT_ENCODING – Acceptable encodings for the response.
    • HTTP_ACCEPT_LANGUAGE – Acceptable languages for the response.
    • HTTP_HOST – The HTTP Host header sent by the client.
    • HTTP_REFERER – The referring page, if any.
    • HTTP_USER_AGENT – The client’s user-agent string.
    • QUERY_STRING – The query string, as a single (unparsed) string.
    • REMOTE_ADDR – The IP address of the client.
    • REMOTE_HOST – The hostname of the client.
    • REMOTE_USER – The user authenticated by the Web server, if any.
    • REQUEST_METHOD – A string such as "GET" or "POST".
    • SERVER_NAME – The hostname of the server.
    • SERVER_PORT – The port of the server (as a string).

    具体使用如:

    def get_headers(request):
        print(request.META['CONTENT_TYPE'])
        return HttpResponse('OK')

    6. 其他HttpRequest对象

    • method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'。
    • user:请求的用户对象。
    • path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。
    • FILES:一个类似于字典的对象,包含所有的上传文件。
    def demo_view(request):
        print(request.META['CONTENT_TYPE'])  # text/plain
        print(request.method)  # GET
        print(request.path)  # /users/demo_view/
        print(request.encoding)
        return HttpResponse('ok')

    Response

    1. HttpResponse

    1) 可以使用django.http.HttpResponse来构造响应对象。

    HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

    也可通过HttpResponse对象属性来设置响应体、状态码:

    • content:表示返回的内容。
    • status_code:返回的HTTP响应状态码。
    def demo_view(request):
        return HttpResponse('python django', status=400)

    image

    2) 响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:

    response = HttpResponse()
    response['python'] = 'django'  # 自定义响应头python, 值为django
    def demo_view(request):
        # return HttpResponse('python django', status=400)
        response = HttpResponse('python django')
        response.status_code = 400
        response['python'] = 'django'
        return response
    

    返回:

    image

    2. HttpResponse子类

    Django提供了一系列HttpResponse的子类,可以快速设置状态码

    • HttpResponseRedirect 301
    • HttpResponsePermanentRedirect 302
    • HttpResponseNotModified 304
    • HttpResponseBadRequest 400
    • HttpResponseNotFound 404
    • HttpResponseForbidden 403
    • HttpResponseNotAllowed 405
    • HttpResponseGone 410
    • HttpResponseServerError 500

    3. JsonResponse

    • 帮助我们将数据转换为json字符串
    • 设置响应头Content-Typeapplication/json
    from django.http import JsonResponse
    def demo_view(request):
        return JsonResponse({"city": "guangzhou"})

    返回

    image

     

    Cookie

    1. 设置cookie

    可以通过HttpResponse对象中的set_cookie方法来设置cookie。

    HttpResponse.set_cookie(cookie名, value=cookie值, max_age=cookie有效期)
    • max_age 单位为秒,默认为None。如果是临时cookie,可将max_age设置为None。

    示例:

    def demo_view(request):
        # return HttpResponse('python django', status=400)
        response = HttpResponse('ok')
        # response.set_cookie('python', 'django')  # 临时cookie
        response.set_cookie('python2', 'django2', max_age=3600)  # 临时cookie
        return response
    

    临时cookie:

    image

    有效期一个小时:

    image

    2. 读取cookie

    可以通过HttpRequest对象的COOKIES属性来读取本次请求携带的cookie值。request.COOKIES为字典类型

    def demo_view(request):
        cookie = request.COOKIES.get('python2')
        print(cookie)
        return HttpResponse('ok')

    返回:

    image

    Session

    1. 启动Django自带session

    可以在settings.py文件中查看,如图所示

    image

    如需禁用session,将上图中的session中间件注释掉即可。

    2. session混合存储(redis)

    在redis中保存session,需要引入第三方扩展,我们可以使用django-redis来解决。

    1) 安装django-redis

    pip install django-redis

    2) 在settings.py文件中做如下设置

    CACHES = {
        "default": {
            "BACKEND": "django_redis.cache.RedisCache",
            "LOCATION": "redis://127.0.0.1:6379/1",
            "OPTIONS": {
                "CLIENT_CLASS": "django_redis.client.DefaultClient",
                "PASSWORD": "redhat",
            }
        }
    }

    注意:

    如果redis的ip地址不是本地回环127.0.0.1,而是其他地址,访问Django时,可能出现Redis连接错误,如下:

    image

    解决办法:

    修改redis的配置文件,添加特定ip地址。

    sudo vim /etc/redis/redis.conf

    image

    重新启动redis服务

    sudo service redis-server restart

    3. session操作

    通过HttpRequest对象的session属性进行会话的读写操作。

    1) 以键值对的格式写session。

    request.session['键']=值
    

    2)根据键读取值。

    request.session.get('键',默认值)
    

    3)清除所有session,在存储中删除值部分。

    request.session.clear()
    

    4)清除session数据,在存储中删除session的整条数据。

    request.session.flush()
    

    5)删除session中的指定键及值,在存储中只删除某个键及对应的值。

    del request.session['键']
    

    6)设置session的有效期

    request.session.set_expiry(value)
    • 如果value是一个整数,session将在value秒没有活动后过期。
    • 如果value为0,那么用户session的Cookie将在用户的浏览器关闭时过期。
    • 如果value为None,那么session有效期将采用系统默认值,默认为两周,可以通过在settings.py中设置SESSION_COOKIE_AGE来设置全局默认值。
  • 相关阅读:
    软件工程第一次作业
    Python正则表达式学习摘要
    个人作业——软件工程实践总结作业
    个人作业——软件评测
    软件工程实践2019第五次作业--结对编程的实现
    软件工程实践2019第四次作业
    软件工程实践2019第三次作业
    软件工程实践2019第二次作业
    软件工程实践2019第一次作业
    个人作业——软件工程实践总结&个人技术博客
  • 原文地址:https://www.cnblogs.com/py-web/p/10900929.html
Copyright © 2011-2022 走看看