首页 > Python框架 > 正文

Django之hello world - Django入门学习教程2

在刚刚安装完成Django后,我们继续来学习Django,本节我们来写Django的第一个程序hello world。好下面我们开始。。。

1. 进入上节我们安装的Django的目录,然后在命令行运行如下命令:

shell# django-admin.py startproject pythontab.com


这样就创建了一个名叫pythontab.com的项目,看一下目录结构:

shell# tree pythontab.com


显示结果:

pythontab.com/

|____ manager.py

|____ Blog/

    |____ urls.py

    |____ wsgi.py

    |____ __init__.py

    |____ settings.py

文件结构中个文件及文件夹的解释:

manager.py是开发过程中要常常使用的文件,顾名思义,就是用来管理的文件,比如创建app,运行shell,运行Django内置的web服务器等等

urls.py文件是Django URL的配置文件,至于当用户访问www.example/post/1254/时,Django会根据url.py的内容来判断这个URL由试图(views)中那个函数来处理,也就是一个路由文件

__init__.py这个文件是空的,python的包都会有一个__init__.py文件。一般不需要修改该文件

wsgi.pywsgi是Web服务器网关接口(Python Web Server Gateway Interface,缩写为WSGI)是Python应用程序或框架和Web服务器之间的一种接口。

settings.py :该  Django  项目的设置或配置。  查看并理解这个文件中可用的设置类型及其默认值。 

下面开始写第一个hello world

打开urls.py文件,然后在文件的最前面加入如下代码:

from django.http import HttpResponse
def hello(request):
    return HttpResponse('hello  world')

然后在patterns(”"),中加入如下代码:

url(r'^$', hello)

完整代码如下:

from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
from django.http import HttpResponse
def hello(request):
    return HttpResponse('hello world')
urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'Blog.views.home', name='home'),
    # url(r'^Blog/', include('Blog.foo.urls')),
    # Uncomment the admin/doc line below to enable admin documentation:
    # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
    # Uncomment the next line to enable the admin:
    # url(r'^admin/', include(admin.site.urls)),
    url(r'^$', hello),
)

然后保存文件

最后,执行在当前目录下的manager.py文件

shell# ./manager runserver


运行启动后端服务

然后我们就可以在浏览器中访问啦!http://127.0.0.1:80 就可以看到输出hello world啦!

很简单吧~~

刚刚入门Django建议阅读《新手学习Django的十条注意事项

上一篇:Django全新安装 - Django入门学习教程1
下一篇:windows环境下Django环境搭建

PythonTab微信公众号:

Python技术交流互助群 ( 请勿加多个群 ):

群1: 87464755

群2: 333646237

群3: 318130924

群4: 385100854