python的django项目中怎么添加app_建立你的第一个python django app

django简单工作逻辑

根据上图,我们可以简单的看出来,我们在访问django网页的时候,url会在urls表中做匹配,如果匹配到了,url表会将匹配到的url下发到指定app的url表中再次进行匹配,匹配成功则运行已定义好的函数,那么由此看来,我们首先得自建一个app。

首先我们建立一个app

(python36env) [root@xxx01 ops]# python manage.py startapp dashboard

(python36env) [root@xxx01 ops]# ls

dashboard db.sqlite3 manage.py ops

建立完成后,我们看到多了一个dashboard的目录

(python36env) [root@xxx01 ops]# tree dashboard/

dashboard/

├── admin.py

├── apps.py

├── __init__.py

├── migrations

│ └── __init__.py

├── models.py

├── tests.py

└── views.py

1 directory, 7 files

目录中有些文件,目前我们先不了解太多,先跑一个hello world再说

1 . 首先我们配置一下app添加

(python36env) [root@xxx01 ops]# vim ops/settings.py

33 INSTALLED_APPS = [

34 'django.contrib.admin',

35 'django.contrib.auth',

36 'django.contrib.contenttypes',

37 'django.contrib.sessions',

38 'django.contrib.messages',

39 'django.contrib.staticfiles',

40 'dashboard.apps.DashboardConfig',

41 ]

打开主程序的ops/settings.py配置文件,然后找到INSTALLED_APPS,在里面将我们刚刚新建的dashboard的项目添加。

这里的路径django已经帮我们处理了,所以我们直接从程序/路径开始写程序的定位即可,具体映射文件的信息如下,这个是建立app的时候自动生成的

(python36env) [root@xxx01 ops]# cat dashboard/apps.py

from django.apps import AppConfig

class DashboardConfig(AppConfig):

name = 'dashboard'

2 . 建立url映射

(python36env) [root@xxx01 ops]# vim ops/urls.py

from django.conf.urls import url,include

from django.contrib import admin

urlpatterns = [

url(r'^admin/', admin.site.urls),

url(r'^dashboard/', include("dashboard.urls")),

]

在这里,我们要导入django.conf.urls中的include模块,然后再添加一条dashboard的映射记录,即当匹配到访问http://x.x.x.x/dashboard/的时候将url传递给dashboard.urls进行二次匹配

3 . 建立dashboard中的urls映射表

这玩意建立app后不会自动生成,我也很懵逼,既然不会自动生成,我们手动建立吧。

由于这玩意是映射视图函数的,我们现在还没有一个视图函数,所以这个映射不咋好写,先搞个视图函数去

(python36env) [root@xxx01 ops]# vim dashboard/views.py

from django.shortcuts import render

from django.http import HttpResponse

# Create your views here.

def index(request):

return HttpResponse("hello world!!")

编写一个index的函数,当被调用的时候通过HttpResponse的方式返回hello world!!

视图编写完成后,再写url映射

(python36env) [root@xxx01 ops]# vim dashboard/urls.py

from django.conf.urls import url

from .views import index

urlpatterns = [

url(r'^hello/',index), #编写映射关系,当访问到hello的时候返回index函数的输出

]

之后启动服务吧

(python36env) [root@xxx01 ops]# python manage.py runserver 0.0.0.0:8000

Performing system checks...

System check identified no issues (0 silenced).

May 26, 2018 - 15:23:52

Django version 1.11.13, using settings 'ops.settings'

Starting development server at http://0.0.0.0:8000/

Quit the server with CONTROL-C.

启动服务后,我们访问下看看效果

hello world!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值