在cmd下创建
# demo1为创建项目名称
django-admin startproject demo1
配置:
settings.py:
import os(全局引入)
ALLOWEN_HOSTS=['*'](配置地址)
启动:
当前文件
python manage.py runserver
此文件下创建其他模块
python manage.py startapp hello
配置hello模块
方法一
#在项目目录下的urls.py文件下配置
#从hello文件夹下的views.py文件引入hello_word函数
#在urls.py的urlpatterns里进行配置
#path配置访问模块的地址,参数1:访问的地址的值,参数2:导入的模块的名称
方法二
#在项目目录下的urls.py文件下配置
#从hello文件夹下的urls.py文件
#在项目的urls.py下引入函数

向浏览器端响应html文件:
1、创建html文件
在项目文件夹的templates文件夹下创建html文件
2、创建函数
3、创建地址,先引入,在创建path()
4、更改setting配置
5、运行程序,结果如下:
获得HTTPRequest请求权信息
def http_request(request):
#1、获得请求方式
print(request.method)
#2、获得请求头信息
headers = request.META
print(headers)
#获取请求头信息的用户代理
ua = request.META.get('HTTP_USER_AGENT',None)
print(ua)
return HttpResponse('响应数据')
响应对象的配置,可以实现服务器响应数据是携带数据,如cookie、状态码等
什么是cookie? 在浏览器在开辟一块空间用于服务器响应的数据
def http_response(request):
# #响应对象携带响应状态码
# resp =HttpResponse("响应内容",status=201)
# print(resp.status_code)
# return resp
#响应cookie
# resp=HttpResponse("响应coookie")
# resp.set_cookie('username','zs')
# resp.set_cookie('password','123456')
# return resp
#响应json格式的字符串
# user_info = {
# 'name':"张三",
# 'password':'123456',
# }
# return JsonResponse(user_info)#注意:导入django.http.JsonResponse包
#响应文件
file_response = FileResponse(open('./hello/tests.py','rb'))
return HttpResponse(file_response)
小结
resonse可响应数据:
状态码、cookie、json、字符串、html代码串、文件
重定向
#重定向,重新访问另外一个地址
# 如访问资源不存在,会返回404状态码,在django中对404状态有预制的配置,如果遇到404则冲定向到django的404页面
def no_data_404(request):
return HttpResponse('404')
#获取文件详情,浏览器地址栏传入文章的id值,文章id值小于1000则触发404
def article_detail(request,article_id):
if article_id < 1000:
#如果访问文章的id值小于1000则访问404的函数地址
return HttpResponseRedirect('/hello/404/')
return HttpResponse('id值是{}的文章内容'.format(article_id))