首页 > 解决方案 > 如何用尽可能少的代码在 django 中自动路由

问题描述

我是 django 的新手。

l 使用 PHP 和 CI。在 CI 中,它可以自动路由。而且我不需要设置太多东西

在教程中,它创建了一个view.py并定义了一个函数,然后在likehello中定义了一个规则,有没有其他方法可以自动路由 url,如下所示urls.pyurl(r'^$', view.hello)

设置一个规则,比如

url(r'^hello/(*)$', view.*)

然后在 view.py 中定义函数

def hello1(request):
    ...
def hello2(request):
    ...

然后访问网址

127.0.0.1:8080/hello/hello1

127.0.0.1:8080/hello/hello2

标签: pythondjango

解决方案


这就是你需要的。

./manage.py
./hello_project/__init__.py
./hello_project/urls.py
./hello_project/hello/__init__.py
./hello_project/hello/urls.py
./hello_project/hello/views.py
./hello_project/settings.py

./hello_project/urls.py

from django.conf.urls import include, url

urlpatterns = [
    url(r'^hello/', include('hello_project.hello.urls')),
]

./hello_project/hello/urls.py

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^hello1', views.hello1),
    url(r'^hello2', views.hello2),
]

./hello_project/hello/views.py

from django.http import HttpResponse


def hello1(request):
    return HttpResponse('hello1\n')

def hello2(request):
    return HttpResponse('hello2\n')

./hello_project/settings.py

..

INSTALLED_APPS = [
    ....
    'hello_project.hello'
]

..

https://docs.djangoproject.com/en/1.11/ref/urls/#url

在行动:

bash-4.4$ curl http://127.0.0.1:8000/hello/hello1
hello1
bash-4.4$ curl http://127.0.0.1:8000/hello/hello2
hello2

PS。不要害怕“代码”/“太多代码行”。看看 python 的禅意来寻找灵感。

完整来源:https ://files.fm/down.php?i=78kartk (可用 2 周,然后它就死了。)


推荐阅读