通过上次的学习,我们已经对Django有了简单的了解,现在来深入了解下~
1. 路由系统
1.1 单一路由对应
a. urls
url(r'^login/', views.login), # login ---> 函数名 views.login
b. templates目录下的login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录</title> </head> <body> <form action="/login/" method="POST" enctype="multipart/form-data"> <p> <input type="text" name="user" placeholder="用户名"/> </p> <p> <input type="password" name="pwd" placeholder="密码"/> </p> <p> 男:<input type="radio" name="sex" value="男"/> 女:<input type="radio" name="sex" value="女"/> </p> <p> <select name="city" multiple="multiple"> <option value="bj" >北京</option> <option value="sh" >上海</option> <option value="sz" >深圳</option> </select> </p> <p> <input type="file" name="upload"/> </p> <p> <input type="submit" value="提交"/> </p> </form> </body> </html>
c. views视图
USER_LIST = {} def login(request): if request.method == 'GET': #判断请求方式 return render(request, 'login.html') elif request.method == 'POST': user = request.POST.get('user') #post请求,单选、输入框获取值 pwd = request.POST.get('pwd') sex = request.POST.get('sex') #多选获取值 city = request.POST.getlist('city') # 上传文件 upload_file_obj = request.FILES.get('upload') print(type(upload_file_obj), upload_file_obj) #<class 'django.core.files.uploadedfile.InMemoryUploadedFile'> 2.jpg #保存上传的文件到upload目录 upload_path = os.path.join('upload', upload_file_obj.name) fw = open(upload_path, 'wb') for line in upload_file_obj.chunks(): #chunks表示所有的数据库,是个迭代器 fw.write(line) fw.close() if user and pwd: USER_LIST['name'] = user USER_LIST['pwd'] = pwd USER_LIST['sex'] = sex USER_LIST['city'] = city USER_LIST['file'] = upload_file_obj.name return render(request, 'success.html', {"user_list": USER_LIST}) else: return HttpResponse('请求不能为空') else: return HttpResponse('请求方式不是getpost') #HttpResponse("字符串")
1.2 基于正则的路由
a. urls 路由设置
# url(r'^detail/', views.detail), #常规url方式,针对某个方法的写法 url(r'^detail-(d+).html', views.detail), #通过正则匹配url,形式是: detail-xx
b, templates目录下的 index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <!-- <ul> {% for k,v in user_dict.items %} <li><a target="_blank" href="/detail/?nid={{ k }}">{{ v.name }}</a></li> {% endfor %} </ul> --> <ul> {% for k,v in user_dict.items %} <li><a target="_blank" href="/detail-{{ k }}.html">{{ v.name }}</a></li> {% endfor %} </ul> </body> </html>
c. views视图
USER_DICT = { "1": {"name": "root1", "email": "qwe1@163.com"}, "2": {"name": "root2", "email": "qwe2@163.com"}, "3": {"name": "root3", "email": "qwe3@163.com"}, "4": {"name": "root4", "email": "qwe4@163.com"}, } def index(request): return render(request, 'index.html', {"user_dict": USER_DICT}) #单一路由对应 # def detail(request): # nid = request.GET.get('nid') #get请求方式,或者到nid的值,即USER_DICT的key # detail_info = USER_DICT[nid] # return render(request, 'detail.html', {"detail_info": detail_info}) #正则路由 def detail(request, nid): # nid指定的是(d+)里的内容 detail_info = USER_DICT[nid] return render(request, 'detail.html', {"detail_info": detail_info})
1.3 正则分组
如果url涉及多个数字拼接,怎么区分接受的数据是nid ? 还是tid?
a, 在url.py增加对应路径
url(r'^index/', views.index), # url(r'^detail/', views.detail), #常规url方式,针对某个方法的写法 # url(r'^detail-(d+).html', views.detail), #通过正则匹配url,形式是: detail-xx url(r'^detail-(?P<nid>d+)-(?P<tid>d+).html', views.detail), #通过正则分组,形式是: detail-xx-xx
b, templates目录下的 index.html
<ul> {% for k,v in user_dict.items %} <li><a target="_blank" href="/detail-{{ k }}-9.html">{{ v.name }}</a></li> {% endfor %} </ul>
c. views视图
#正则路由 # def detail(request, nid): # # nid指定的是(d+)里的内容 # detail_info = USER_DICT[nid] # return render(request, 'detail.html', {"detail_info": detail_info}) def detail(request, **kwargs): print(kwargs) # {'nid': '1', 'tid': '9'} nid = kwargs.get("nid") detail_info = USER_DICT[nid] return render(request, 'detail.html', {"detail_info": detail_info})
1.4 为路由映射名称
如接口名称进行了变更,多次变更,涉及的trmplates、views 都需要进行修改,有什么办法可以解决这种方式? urls 路由设置name。
a, 在url.py增加name属性
urlpatterns = [ url(r'^asdfasdf/', views.exmplas_urls, name="demo1"), url(r'^buy/(d+)', views.exmplas_urls, name="demo2"), url(r'^check/(?P<nid>d+)/(?P<tid>d+)', views.exmplas_urls, name="demo3"), ]
b. view视图
#为路由映射名称 def exmplas_urls(request): if request.method == 'POST': user = request.POST.get('user') return render(request, 'demo.html', {'user': user}) else: return render(request, 'demo.html') #为路由映射名称 def exmplas_urls(request, nid): print(nid) if request.method == 'POST': user = request.POST.get('user') return render(request, 'demo.html', {'user': user}) else: return render(request, 'demo.html') #为路由映射名称 def exmplas_urls(request, **kwargs): print(kwargs) #{'nid': '3', 'tid': '9'} if request.method == 'POST': user = request.POST.get('user') return render(request, 'demo.html', {'user': user}) else: return render(request, 'demo.html')
c. templates目录下的 demo.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>urls映射名称</title> </head> <body> <!--1. 常规写法 action="/asdfasdf/" 优化写法:action="{% url "demo1" %}" 2. url正则 action="buy/6" 优化写法: action = {% url "demo2" 6 %} 3. url分组 action = "check/6/9" 优化写法: action = {% url "demo3" nid=3 tid=9 %} --> {{ user }} <form action="{% url "demo3" nid=3 tid=9 %}" method="POST"> <p><input type="text" name="user" placeholder="用户名"/></p> <p><input type="password" name="pwd" placeholder="密码"/></p> <p><input type="submit" name="提交"/></p> </form> </body> </html>
1.5 获取当前URL
view.py中配置:
def login(request): print(request.path_info) return render(request, 'path.html')
在templates目录下的path.html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>当前URL</title> </head> <body> <h1>当前url: {{ request.path_info }}</h1> <form action="{{ request.path_info }}" method="POST"> <p><input type="text" name="user" placeholder="用户名称"/></p> <p><input type="submit" value="刷新"/></p> </form> </body> </html>
页面访问效果
1.6 根据app对路由分类
主程序urls.py文件
from django.contrib import admin from django.conf.urls import url,include from cmdb import views urlpatterns = [ url(r'cmdb/', include('cmdb.urls')), url(r'cmdb02/', include('cmdb02.urls')), ]
cmdb下的urls.py文件
from django.conf.urls import url from cmdb import views urlpatterns = [ url(r'login/', views.login) ]
cmdb02下的urls.py文件
from django.conf.urls import url from cmdb02 import views urlpatterns = [ url(r'login/', views.login) ]
页面访问: