当前位置: 移动技术网 > IT编程>脚本编程>Python > Python Web开发:使用Django框架创建HolleWorld项目

Python Web开发:使用Django框架创建HolleWorld项目

2019年06月24日  | 移动技术网IT编程  | 我要评论

玛克纳尔必须死,政府部门工作总结,梦之队劳资协议书

开发环境搭建

python环境安装


django安装

打开windows cmd输入pip install django

pycharm ide(社区版)安装


创建helloworld项目

通过django的startproject命令在目录中创建项目


如下图就是通过startproject命令创建的项目文件结构

  • manage.py 项目的管理文件
  • settings.py 项目的配置文件
  • urls.py 项目的路由管理文件
  • wsgi.py 是wsgi接口相关信息


项目创建完成后,可通过终端命令runserver直接启动

#如果有类似异常,可能是django没有安装好,在终端中再重装一次django包(pip install django)
traceback (most recent call last):
  file "manage.py", line 10, in main
    from django.core.management import execute_from_command_line
modulenotfounderror: no module named 'django'

the above exception was the direct cause of the following exception:

traceback (most recent call last):
  file "manage.py", line 21, in <module>
    main()
  file "manage.py", line 16, in main
    ) from exc
importerror: couldn't import django. are you sure it's installed and available on your pythonpath environment variable? did you forget to activate a virtual environment?

系统检测文件没有问题后,会启动服务

watching for file changes with statreloader
performing system checks...

system check identified no issues (0 silenced).

you have 17 unapplied migration(s). your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
run 'python manage.py migrate' to apply them.
june 23, 2019 - 15:57:10
django version 2.2.2, using settings 'hello_world.settings'
starting development server at http://127.0.0.1:8000/

然后用浏览器打开http://127.0.0.1:8000/,能够正常打开页面,说明一切正常

通过django的startapp命令在项目中创建应用包


在shop包中,各文件的说明

  • views.py 视图处理
  • tests.py 测试用例
  • models.py 定义应用模型
  • apps.py 声明应用
  • admin.py 定义admin模块管理对象

在项目中添加一个新的视图

在views.py文件中,新增hello()函数

from django.shortcuts import render

from django.http import httpresponse

# create your views here.

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

增加视图函数之后,我们还需要对路由进行配置,将视图和url进行绑定,不然在网页上是无法浏览到我们添加的视图

路由配置

首先在shop包中创建一个urls.py路由文件,,这是应用层次的路由配置

from django.urls import path

import shop.views

urlpatterns = [
    path('hello', shop.views.hello)
]

然后还需要对项目层次的路由进行配置,打开hello_world包下的urls.py文件,然后增加path('shop/', include('shop.urls')),如果请求地址中含有shop就转发到刚才配置的shop.urls路由文件中

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('shop/', include('shop.urls'))
]

项目主程序中添加应用

打开settings.py文件,然后进行引用配置(这里配置的方法shopconfig是在创建应用的时候自动生成的apps.py文件中的一个方法)

客户请求的过程

最后

现在所有的配置我们已经完成,可以通过runserver命令启动服务,打开浏览器输入http://127.0.0.1:8000/shop/hello,到此我们一个基本的helloworld项目已经算是创建完成

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网