python - 如何用尽可能少的代码在 django 中自动路由
问题描述
我是 django 的新手。
l 使用 PHP 和 CI。在 CI 中,它可以自动路由。而且我不需要设置太多东西
在教程中,它创建了一个view.py
并定义了一个函数,然后在likehello
中定义了一个规则,有没有其他方法可以自动路由 url,如下所示urls.py
url(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
解决方案
这就是你需要的。
./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 周,然后它就死了。)
推荐阅读
- javascript - 使用 addEventListener 的 js onclick 随机文本
- javascript - Brain.js 正确训练神经网络
- python - 使用带有 Firefox 的 python http 代理
- html - 在 rails .erb 文件中转义特殊字符
- java - 第一个参数类型错误
- xamarin - 如何隐藏 Grid 行和 ListView 列,以便看不到任何空白空间?
- python - 如何从字符串更改 qlabel 的字体?
- javascript - 自定义滚动条不滚动
- docker - 当前上下文中没有构建阶段 - Docker 文件
- asp.net - 在 ASP.NET MVC 中检索作为字节数组的表单字段