首页
登录 | 注册

[举重若轻]python+django+mysql web开发入门学习之hello world

创建项目

部署好环境之后,要开发一个web程序,首先我们要建立一个项目:


如果系统找不到django-admin.py命令,可以到python的bin目录下查找。这个命令会创建一个项目目录mysite,它下面的目录详情如下:

├── manage.py
└── mysite
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    └── wsgi.py

manage.py:包含了所有与项目交互的命令,比较启动服务器、连接数据库、打开shell等功能;

mysite/__init__.py:是项目的初始文件,一开始是一个空的文件;

mysite/settings.py:是项目的配置文件 ,如数据库连接、模板地址等;

mysite/urls.py:是项目的url映射文件,可以指定哪些url由哪些module来处理,类似于apache的httpd.conf文件;

mysite/wsgi.py:python的web服务器网关服务中间件。


启动服务


你可以指定ip,如果不指定则为localhost。然后你可以访问http:127.0.0.1:8080来访问,如果正常会显示如下:
It worked!
Congratulations on your first Django-powered page.

Of course, you haven't actually done any work yet. Here's what to do next:
If you plan to use a database, edit the DATABASES setting in mysite1/settings.py.
Start your first app by running python manage.py startapp [appname].
You're seeing this message because you have DEBUG = True in your Django settings file and you haven't configured any URLs. Get to work!

创建hello world的处理module

在mysite下(与manage.py同级的mysite下)创建一个文件views.py,内容如下:
from django.http import HttpResponse

def hello(request):
   return HttpResponse("hello world")

然后将这个module放到urls.py的映射中:
from django.conf.urls import patterns, include, url

# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'mysite1.views.home', name='home'),
    # url(r'^mysite1/', include('mysite1.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/', 'mysite1.views.hello',name='hello'),
)

最后一行即为新加的将http://127.0.0.1:8080/hello映射到views下的hello函数来处理。然后就可以启动服务,然后在浏览器中查看了。


2020 jeepxie.net webmaster#jeepxie.net
10 q. 0.008 s.
京ICP备10005923号