接上一篇, 使用有名参数 可以方便传参 views接收参数顺序不需要固定
ret=re.search("d(?P<id>\d+)","32asd34szDxz34")
?P<id> 定义正则匹配的名字
以下示例中匹配为year month
urls
"""Dajon_demo URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^index/', views.index),
url(r'^login_in/', views.login_in),
#有名分组
url(r'^articles/(?P<year>\d{4})/(?P<month>\d{2})$', views.year_month),
# 无名分组 传参 ()中为参数 类似re.findall
url(r'^articles/(\d{4})$',views.year),
url(r'^articles/(\d{4})/(\d{2})', views.month),
]
views
from django.shortcuts import render, HttpResponse
# Create your views here.
import datetime
def index(request):
timer = datetime.datetime.now()
return HttpResponse(timer)
def login_in(request):
if request.method == "POST":
# print("=====>", request.POST)
username = request.POST.get("user")
password = request.POST.get("pwd")
if username == "yuan" and password == "123":
return HttpResponse("登陆成功")
return render(request, "lgoin_in.html")
def year(request, year):
return HttpResponse(year)
def month(request, year, month):
return HttpResponse("year: %s month:%s" % (year, month))
def year_month(request, year, month):
return HttpResponse("year: %s month:%s" % (year, month))