python---django中url訪問方法


只是了解,不推薦使用,畢竟干擾太多,任意沖突,也沒有解耦,應該使用路由分發

在url匹配中支持正則匹配,例如:

from django.conf.urls import include, url
from django.contrib import admin
from blog import views
from ts import views as v2

urlpatterns = [ url(r'^$', 'HelloWorld.views.home', name='home'), ]

訪問方法一:

url(r'^userinfo',views.userinfo),

匹配以userinfo開頭,但是不一定以其結尾,在后面加上其他后綴也是允許的

http://127.0.0.1:8080/userinfo
http://127.0.0.1:8080/userinfodasf

訪問方法二:

url(r'^article/2013/66$',v2.show_url),

匹配以article開始,66結尾,格式按照,但是在中間加入其他也是允許的:

http://127.0.0.1:8080/article/2013/66
http://127.0.0.1:8080/article/2013d/d66

訪問方法三:

url(r'^article/([0-9]{4})/$',v2.show_url_3),

在()中數據是為傳入參數

http://127.0.0.1:8080/article/2012/

可獲取,處理,但是獲取方法不不受限制:

def show_url_3(req,*argc):return HttpResponse("<h1>year"+argc[0]+"</h1>")

def show_url_3(req,y): return HttpResponse("<h1>year"+y+"</h1>")

訪問方法四:

url(r'^article/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$',v2.show_url_4),

限制傳參,參數名必須一致:

http://127.0.0.1:8080/articel/2012/23/
def show_url_4(req,year,month):

    return HttpResponse("<h1>year:"+year+"\tmonth:"+month+"</h1>")

訪問方法五:

url(r"^index",views.index,{'name':'ld'}),

后台自定義傳參:作用:例如對於不同情況,傳入不同模板文件名,同一函數處理時獲取不同文件名,進行渲染返回(實際不用這種方法),訪問直接使用index即可,但是函數傳參名必須一致:

def index(req,name):
    return HttpResponse("<h1>ok</h1>")

訪問方法六:

url(r'^login',views.login,name="lg"),

為方法設置別名,可以在前端使用時簡寫,在返回給客戶端 時,在渲染時會被替換為原來路徑

def login(req):
    if req.method == "POST":
        if req.POST.get("username",None)=="fsaf" and req.POST.get("password",None)=="123456":
            return HttpResponse("<h1>ok</h1>")
    return render(req, "login.html")

使用方法:

    <form action="{% url 'lg' %}" method="post">
        <input type="text" name="username"/>
        <input type="password" name="password"/>
        <input type="submit">
    </form>

 也可以進行傳參:

url(r'^all/(?P<article_type_id>\d+)\.html$',home.index,name='index'),

在視圖函數中使用:

reverse("index",kwargs={"article_type_id":1}) ==> all/1.html

 

在HTML代碼中進行使用:

{% url "index" article_type_id=1 %}  ==>  all/1.html

 或者:

url(r'^all/(\d+)\.html$',home.index,name='index'),
reverse("index",args=(2,)) ==> all/2.html
{% url "index" 2 %}  ==>  all/2.html

 注意引入:

from django.core.urlresolvers import reverse

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM