准备

自己写一个简单的webServer

 import socket

 # 生成socket实例对象
sk = socket.socket()
# 绑定IP和端口
sk.bind(("127.0.0.1", 8001))
# 监听
sk.listen()
# 写一个死循环,一直等待客户端来连我
while 1:
conn, _ = sk.accept()
data = conn.recv(8096)
data_str = str(data, encoding="utf-8")
# 给客户端回复消息
conn.send(b'http/1.1 200 OK\r\ncontent-type:text/html; charset=utf-8\r\n\r\n')
# 拿到函数的执行结果
response = b'from socket server'
# 将函数返回的结果发送给浏览器
conn.send(response)
# 关闭连接
conn.close()

wsgiref实现的webServer

 import time
from wsgiref.simple_server import make_server def func1():
return 'from func1' def run_server(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息
url = environ['PATH_INFO'] # 取到用户输入的url
print(url) # /func1
response = ''
if url == '/func1':
response = eval(url[1:] + '()')
response = bytes(response, encoding='utf8')
return [response, ] if __name__ == '__main__':
httpd = make_server('127.0.0.1', 8090, run_server)
print("我在8090等你哦...")
httpd.serve_forever()

jinja2模板引擎

安装: pip3 install jinja2

 from wsgiref.simple_server import make_server
from jinja2 import Template def index():
with open("user_template.html", "r", encoding="utf-8") as f:
data = f.read()
template = Template(data) # 生成模板文件
# 从数据库中取数据
import pymysql conn = pymysql.connect(
host="127.0.0.1",
port=3306,
user="root",
password="root",
database="pythontestdb",
charset="utf8",
)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select * from userinfo;")
user_list = cursor.fetchall()
# 实现字符串的替换
ret = template.render({"user_list": user_list}) # 把数据填充到模板里面
return [bytes(ret, encoding="utf8"), ] def home():
with open("home.html", "rb") as f:
data = f.read()
return [data, ] # 定义一个url和函数的对应关系
URL_LIST = [
("/index", index),
("/home", home),
] def run_server(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html;charset=utf8'), ]) # 设置HTTP响应的状态码和头信息
url = environ['PATH_INFO'] # 取到用户输入的url
func = None # 将要执行的函数
for i in URL_LIST:
if i[0] == url:
func = i[1] # 去之前定义好的url列表里找url应该执行的函数
break
if func: # 如果能找到要执行的函数
return func() # 返回函数的执行结果
else:
return [bytes("404没有该页面", encoding="utf8"), ] if __name__ == '__main__':
httpd = make_server('', 8000, run_server)
print("Serving HTTP on port 8000...")
httpd.serve_forever()

Code

 <!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="x-ua-compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Title</title>
</head>
<body> <table border="1">
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
{% for user in user_list %}
<tr>
<td>{{user.id}}</td>
<td>{{user.name}}</td>
<td>{{user.age}}</td>
<td>{{user.sex}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</body>
</html>

user_template.html

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<body>
<h1>Home</h1>
</body>
</html>

home.html


db

django的安装与使用

介绍

  • 支持时间图

  • python版本支持对照表

    django版本 python版本
    1.5.x 2.6.5|2.7|3.2|3.3
    1.6.x 2.6|2.7|3.2|3.3
    1.7.x 2.7|3.2|3.3|3.4
    1.8.x 2.7|3.2|3.3|3.4|3.5
    1.9.x 2.7|3.4|3.5
    1.10.x 2.7|3.4|3.5
    1.11.x(开发推荐) 2.7|3.4|3.5|3.6
    2.0.x 3.4|3.5|3.6

安装

  • 使用cmd安装

    pip3 install django # 默认安装当前最高版本
    pip3 install django==1.11.15 # 用==安装指定版本
  • 使用pycharm安装



使用

  • 配置相关

    • settings.py
       TEMPLATES = [
      {
      'BACKEND': 'django.template.backends.django.DjangoTemplates',
      'DIRS': [
      os.path.join(BASE_DIR, 'templates1'), # 根目录->templates1
      os.path.join(BASE_DIR, 'templates2'), # 根目录->templates2
      ], # 配置render()函数在上述路径下寻找模板
      'APP_DIRS': True,
      'OPTIONS': {
      'context_processors': [
      'django.template.context_processors.debug',
      'django.template.context_processors.request',
      'django.contrib.auth.context_processors.auth',
      'django.contrib.messages.context_processors.messages',
      ],
      },
      },
      ]

      Templates节:配置模板存放位置

       # 静态文件保存目录的别名
      STATIC_URL = '/static/' # 静态文件存放文件夹
      STATICFILES_DIRS = [
      os.path.join(BASE_DIR, "static1"),
      os.path.join(BASE_DIR, "static2"),
      ]
      # 上述配置的效果就是 请求指定别名会在指定目录下寻找指定文件
      # 例:127.0.0.1:8000/static/test.css 会在STATICFILES_DIRS节中配置的每个目录寻找名为test.css的文件

      STATIC_URL&STATICFILES_DIRS节:配置静态文件存放目录

  • 创建Django项目

    • 命令行创建
      django-admin startproject 项目名
    • pycharm创建
      File --> New project --> 左侧选Django --> 右侧填项目路径-->Create
    • 目录结构如下

  • Django项目的运行

    • 命令行运行
      在项目的根目录下(也就是有manage.py的那个目录),运行:
      python3 manage.py runserver IP:端口--> 在指定的IP和端口启动
      python3 manage.py runserver 端口 --> 在指定的端口启动
      python3 manage.py runserver --> 默认在本机的8000端口启动
    • pycharm运行

      点绿色的小三角,直接可以启动Django项目(前提是小三角左边是你的Django项目名)

  • Hello Django

    • 编辑urls.py
       from django.conf.urls import url
      from django.contrib import admin def hello(request):
      from django.shortcuts import HttpResponse
      return HttpResponse('Hello Django') urlpatterns = [
      url(r'^admin/', admin.site.urls),
      url(r'^hello/',hello)
      ]

      urls.py

    • 运行
      Performing system checks...
      
      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.
      September 18, 2018 - 14:27:53
      Django version 1.11.15, using settings 'django_first_prj.settings'
      Starting development server at http://127.0.0.1:8000/
      Quit the server with CTRL-BREAK.

      console

python框架之Django(1)-第一个Django项目的更多相关文章

  1. Python开发入门与实战2-第一个Django项目

    2.第一个Django项目 上一章节我们完成了python,django和数据库等运行环境的安装,现在我们来创建第一个django project吧,迈出使用django开发应用的第一步. 2.1.创 ...

  2. django创建第一个django项目-2

    安装django 虚拟环境下执行命令: pip install django==1.11.11 查看是否安装成功 pip list 列表中有django说明安装成功 创建工程 命令行移动到想要创建项目 ...

  3. Django安装+创建一个Django项目

    安装 选用pycharm    在终端输入命令:pip install django 安装完成后创建项目 1.在你想创建项目的目录下输入下面的代码 2.django-admin startprojec ...

  4. SSM框架搭建——我的第一个SSM项目

    转载自:http://blog.csdn.net/tmaskboy/article/details/51464791 作者使用MyEclipse 2014版本 本博客所编写程序源码为: http:// ...

  5. dya49:django:wsgrief&模板渲染Jinjia2&django的MTV/MVC框架&创建/启动一个django项目

    目录 1.自定义web框架wsgiref版 2.自定义web框架wsgiref版-优化版 3.模板渲染JinJa2 4.MTV和MVC框架 5.django:下载安装&创建启动 自定义web框 ...

  6. 编写你的第一个Django应用

    安装 Python 作为一个 Python Web 框架,Django 需要 Python.更多细节请参见 我应该使用哪个版本的 Python 来配合 Django?. Python 包含了一个名为  ...

  7. 第一个Django应用

    Django教程:http://www.liujiangblog.com/course/django/2 第一个Django应用 该应用包括以下两个部分: 一个可以让公众用户进行投票和查看投票结果的站 ...

  8. python框架之django

    python框架之django 本节内容 web框架 mvc和mtv模式 django流程和命令 django URL django views django temple django models ...

  9. 第六篇:web之python框架之django

    python框架之django   python框架之django 本节内容 web框架 mvc和mtv模式 django流程和命令 django URL django views django te ...

随机推荐

  1. 快速开发项目,用到的工具:UI 设置利器 sketch

    需求设计: axaure8.0 tool: teambition/石墨.幕布. 接口管理tool(后端开发接口,pc,m,app使用) https://www.eolinker.com/#/ ui 设 ...

  2. Python threading 多参数传递方法

    今天开启线程传递参数的时候,出现了一个小问题,一直不能传递多个参数,如下 import threading thread1 = threading.Thread(target=fun, args=[1 ...

  3. SetProcessWorkingSetSize减少内存占用

    [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")] public stat ...

  4. Android全面屏适配

    什么是全面屏 概念 很多人可能把全面屏跟曲面屏混淆,其实这是两个不同的概念. 一般手机的屏幕纵横比为16:9,如1080x1920.1440x2560等,其比值为1.777777……,全面屏手机出现之 ...

  5. Houdini技术体系 基础管线(四) :Houdini驱动的UE4植被系统 上篇

    背景 之前在<Houdini技术体系 过程化地形系统(一):Far Cry5的植被系统分析>一文中已经对AAA游戏中过程化植被的需求有了一定的定义,后续工作就是如何用Houdini开发功能 ...

  6. Angular4学习笔记-目录汇总

    Angular4学习笔记(一)-环境搭建 Angular4学习笔记(二)-在WebStorm中启动项目 Angular4学习笔记(三)- 路由 Angular4学习笔记(四)- 依赖注入 Angula ...

  7. 【Dubbo 源码解析】04_Dubbo 服务注册&暴露

    Dubbo 服务注册&暴露 Dubbo 服务暴露过程是通过 com.alibaba.dubbo.config.spring.ServiceBean 来实现的.Spring 容器 refresh ...

  8. Servlet开发 中使用 log4jdbc 记录 hibernate 的 SQL信息

    一.前言 使用log4jdbc在不改变原有代码的情况下,就可以收集执行的SQL文和JDBC执行情况. 平时开发使用的ibatis,hibernate,spring jdbc的sql日志信息,有一点个缺 ...

  9. Non-zero exit code (1)

    刚报了这个错Non-zero exit code (1) 经排查执行这个命令就好了  python -m pip install --upgrade pip 一定要多看报错,报错中有提示的

  10. C# WinForm窗体隐藏右上角最小化、最大化、关闭按钮

    C# WinForm窗体隐藏右上角最小化.最大化.关闭按钮 如何赢藏WinForm窗体的右上角按钮  设置设置ControlBox = false: 设置ControlBox = false: