首页 > 代码库 > 【17】Django

【17】Django

Python Web框架

  • 自己实现socket

   Tornado

  • 基于wsgi:wsgi.run(ip.port)

   Django

自己开发we框架

from wsgiref.simple_server import make_serverdef RunServer(environ, start_response):    start_response(‘200 OK‘, [(‘Content-Type‘, ‘text/html‘)])    return ‘<h1>Hello, web!<h1>‘if __name__ == ‘__main__‘:    httpd = make_server(‘‘, 8000, RunServer)    print("Serving HTTP on port 8000...")    httpd.serve_forever()

Web框架

Web框架

处理用户请求

放置HTML模版

操作数据库

框架

MVC

Controllers

Views

Modals

 

MTV

Views

Template

Modals

Django

 

 

 

 

 

Django

1. 安装Django

pip3 install django# 添加环境变量

2. 创建Project

django-admin startproject mysite
######################################### mysite目录 mysite│ manage.py # diango程序启动文件│└─mysite settings.py # 配置文件 urls.py # 路由系统 wsgi.py # WSGI __init__.py

3. 创建APP

cd mysitepython manage.py startapp cmdb###################################cmdb目录│  admin.py        # 后台管理配置模块│  apps.py         #│  models.py       # 数据库管理配置模块│  tests.py        # 单元测试模块│  views.py        # 处理用户请求模块

4. 编写代码

urls.py

from django.conf.urls import urlfrom django.contrib import adminfrom cmdb import viewsurlpatterns = [    # url(r‘^admin/‘, admin.site.urls),    url(r‘^index/‘, views.index),]

view.py 函数

from django.shortcuts import renderfrom django.shortcuts import HttpResponse# Create your views here.# 处理用户请求def index(request):    return HttpResponse(‘Hello Web !‘)

5. 启动Django程序

# 执行命令python manage.py runserver 127.0.0.1:8000# 启动信息System check identified no issues (0 silenced).You have 13 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.August 28, 2016 - 19:01:32Django version 1.10, using settings ‘mysite_django.settings‘Starting development server at http://127.0.0.1:8000/Quit the server with CTRL-BREAK.

页面显示结果

 技术分享

6. 使用模版

settings配置

render(request, ‘路径‘)

7.  静态文件的配置

8.  基本提交数据

9. 连接数据库、操作数据库

ORM

settings.py

models.py

10. 注册app

执行命令创建数据库:

python manage.py makemigrationspython manage.py migrate

11. 操作数据库

创建:

models.类.object.create(user=u,email=e)

获取:

models.类.object.all()

 

【17】Django