Hello World跑起来
django下载
pip install django
Hello World跑起来
使用Django快速搭建一个web服务
新建demo目录,进入demo目录
mkdir demo
cd demo
demo目录中,创建项目helloworld
django-admin startproject helloworld
cd helloworld
项目helloworld中创建一个app,名为newapp
查看目录
python manage.py startapp newapp
dir(or ls)
看下项目目录结构 tree /F(win) | tree (linux)
.
├── newapp
│ ├── admin.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── helloworld
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ └── settings.cpython-36.pyc
│ ├── settings.py
│ ├── urls.py
│ └── wsgi.py
└── manage.py
新建的app newapp添加到默认配置中./helloworld/settings.py
,在INSTALLED_APPS
数组中添加app newapp
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'newapp',
)
编辑newapp目录中的视图view.py文件
#coding: utf-8
from django.shortcuts import render
# 加入http响应模块
from django.http import HttpResponse
# 定义函数index做响应
def index(request):
# 响应为字符串Hello World
return HttpResponse(u'Hello World')
为刚才的view视图配置url路由,编辑./helloworld/urls.py
from django.conf.urls import include, url
from django.contrib import admin
#导入newapp view视图
from newapp import views as newapp_views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
# 当请求首页时,响应为newapp中的index方法
url(r'^$', newapp_views.index)
]
运行web服务器
python manage.py runserver 0.0.0.0:8000
浏览器测试成功
回顾操作步骤
.
├── newapp 2 创建app
│ ├── admin.py
│ ├── __init__.py
│ ├── migrations
│ │ └── __init__.py
│ ├── models.py
│ ├── tests.py
│ └── views.py 3 修改views.py(导入request模块 写index方法)
├── helloworld 1 创建project
│ ├── __init__.py
│ ├── __pycache__
│ │ ├── __init__.cpython-36.pyc
│ │ └── settings.cpython-36.pyc
│ ├── settings.py 4 配置文件添加app
│ ├── urls.py 5 设置路由(导入view视图,写路由规则)
│ └── wsgi.py
└── manage.py