1.请求响应对象

1.1 请求对象HttpRequest测试
#hello\views
def http_request(request):
    #1.获得请求方式
    print(request.method)
    #2.获得请求头信息
    #2.1 获取META中的请求头信息
    headers = request.META
    print(headers)
    #2.2 获取请求头信息的内容
    ua = request.META.get('HTTP_USER_AGENT',None)
    #2.3 通过headers获取请求头信息
    print(request.headers)
    print(request.headers['User-Agent'])
    print(ua)
    #3.获取请求参数
    name = request.GET.get('name','')
    print(name)
    return HttpResponse('响应')
#hello\urls
path('http/resp/',http_response,name='http_response'),1.2 请求对象HttpResponse测试
#hello/urls
path('http/resp/',http_response,name='http_response'),1.2.1 设置响应状态码
#hello/views
def http_response(request):
    resp = HttpResponse('响应状态码',status=201)
    print(resp.status_code)#获得响应对象中的状态码
    return resp1.2.2 响应cookie
    resp = HttpResponse('响应Cookie')
    #注意:cookie数据要求不能有特殊字符及汉字,只允许英文字母和数字
    resp.set_cookie('username','badada',max_age=604800)
    resp.set_cookie('password','0603',max_age=604800)
    return resp1.2.3 响应JSON格式数据
   JSON是前后端传递数据的标准格式,数据内容由key:value组成
    在json中可以通过符号表示对象及列表
    包含的数据类型:字符数字、布尔、对象、列表
    """
    如:
    {
        id:1,
        name:'badada'
        like:['吃','喝','旅游']
    }
    """
    user_info = {
        'name':'badada',
        'age':32,
        'like':['吃','喝','旅游']
    }
    return JsonResponse(user_info)1.2.4 响应文件
    response = FileResponse(open('./hello/tests.py','rb'))
    return response2.重定向
如果文章id大于1000,则表示该文章不存在,重定向至404页面
重定向至沾点内部的url地址
return HttpResponseRedirect('/hello/404/')
重新向至站点内部的视图名或者重定向至站点外部资源
#hello/urls
    path('404/',no_data_404,name='no_data_404'),
    path('article/detail/<int:article_id>', article_detail, name='article_detail'),
#hello/views
def no_data_404(request):
    #404页面
    return HttpResponse('404')
def article_detail(request,article_id):
    if article_id>1000:
        return redirect('https://www.baidu.com')
    return HttpResponse('文章{}の内容'.format(article_id))3.重写内置的错误处理视图
3.1 配置自定义 500 错误页面
test_django的settings 中更改是否支持debug运行
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False 在test_django中新建views文件
#test_django/views:
from django.http import HttpResponse
def page_500(request):
    return HttpResponse('服务器正忙,稍后重试')
#test_django/urls:
handler500 = "test_django.views.page_500"3.2 配置hello网址错误页面
#hello/views
def page_500(request):
    raise #触发异常
    return HttpResponse('错误页面')
#hello/urls
    path('page_500/',page_500,name='page_500'),4.配置处理静态文件
新建medias文件夹,与hello、test_django同级。
用于存放静态文件,如图片等。
#test_django/settings
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False 
#test_django/settings:
MEDIA_URL = '/media/'#配置目录资源地址
MEDIA_ROOT = os.path.join(BASE_DIR,'medias')#存放静态资源文件
#test_django/urls:
from test_django import settings
from test_django import re_path
from django.views.static import serve
if settings.DEBUG:
    urlpatterns += [
        re_path(r"^media/(?P<path>.*)$",
            serve, {
                "document_root": settings.MEDIA_ROOT
            }),
    ]5.Class重写视图
temples文件夹下新建home.html模板文件:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>home首页</h1>
</body>
</html>用函数访问该模板文件:
# hello/views:
class HomeView(TemplateView):
    template_name = 'home.html'
# hello/urls:
path('homeview/',HomeView.as_view(),name='HomeView'),6.创建姓名模板
username里的数据发生改变,页面中渲染的数据发生改变,该效果称为动态数据
#hello/views:
def hello_user(request):
    username='000'
    html= '''
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Title</title>
        </head>
        <body>
            <h1 style='color:#f00;'>hello{{username}}</h1>
        </body>
    </html>
    '''.replace('{{username}}',username)
    return HttpResponse(html)
# hello/urls:
    path('hello_user/', hello_user, name='hello_user'),

















