python学习笔记_week18
note
View Code
1、JS 正则 test - 判断字符串是否符合规定的正则 rep = /\d+/; rep.test("asdfoiklfasdf89asdfasdf") # true rep = /^\d+$/; rep.test("asdfoiklfasdf89asdfasdf") # true exec - 获取匹配的数据 rep = /\d+/; str = "wangshen_67_houyafa_20" rep.exec(str) # ["67"] JavaScript is more fun than Java or JavaBeans! var pattern = /\bJava(\w*)\b/; # ["JavaScript", "Script"] JavaScript is more fun than Java or JavaBeans! var pattern = /\bJava\w*\b/g; # ["JavaScript"] # ["Java"] # ["JavaBeans"] # null JavaScript is more fun than Java or JavaBeans! var pattern = /\bJava(\w*)\b/g; # ["JavaScript",'Script'] # ["Java", ""] # ["JavaBeans", "Beans"] # null 多行匹配: 默认就是多行匹配 ^$ - 登录注册验证 默认事件先执行: checkbox 自定义先执行 a submit ... <form> <input type='type' /> <input type='password' /> <input type='submit' /> </form> $(':submit').click(function(){ $(':text,:password').each(function(){ ... return false; }) return false; }) input,checbox ================================== 验证 ================================ JS: 验证 各种验证 $(':submit').click(function(){ $(':text,:password').each(function(){ ... return false; }) return false; }) 后端:python实现 业务处理 .... 2、组件 BootStrap ===全栈 - css - js 学习 BootStrap 规则 一、响应式 @media 二、图标、字体 @font-face 三、基本使用 ========》 后台管理 jQueryUI * - css - js 学习 jQueryUI 规则 EasyUI - css - js 学习 jQueryUI 规则 bxslider 轮播图 ============ Ajax操作 ================ 3、WEB框架 MVC Model View Controller 数据库 模板文件 业务处理 MTV Model Template View 数据库 模板文件 业务处理 ############## WEB:MVC、MTV 4、Django pip3 install django C:\Python35\Scripts # 创建Django工程 django-admin startproject 【工程名称】 mysite - mysite # 对整个程序进行配置 - init - settings # 配置文件 - url # URL对应关系 - wsgi # 遵循WSIG规范,uwsgi + nginx - manage.py # 管理Django程序: ---django也有orm框架 - python manage.py - python manage.py startapp xx - python manage.py makemigrations - python manage.py migrate # 运行Django功能 python manage.py runserver 127.0.0.1:8001 chouti - chouti - 配置 - 主站 app - 后台管理 app # 创建app python manage.py startapp cmdb python manage.py startapp openstack python manage.py startapp xxoo.... app: migrations 数据修改表结构 admin Django为我们提供的后台管理 apps 配置当前app models ORM,写指定的类 通过命令可以创建数据库结构 tests 单元测试 views 业务代码 创建完project之后 1、配置模板的路径 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] 2、配置静态目录 static STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) <link rel="stylesheet" href="/static/commons.css" /> 内容整理 1. 创建Django工程 django-admin startproject 工程名 2. 创建APP cd 工程名 python manage.py startapp cmdb 3、静态文件 project.settings.py STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) 4、模板路径 DIRS ==> [os.path.join(BASE_DIR,'templates'),] 5、settings中 middlerware # 注释 csrf 6、定义路由规则 url.py "login" --> 函数名 7、定义视图函数 app下views.py def func(request): # request.method GET / POST # http://127.0.0.1:8009/home?nid=123&name=alex # request.GET.get('',None) # 获取请求发来的而数据 # request.POST.get('',None) # return HttpResponse("字符串") # return render(request, "HTML模板的路径") # return redirect('/只能填URL') 8、模板渲染 特殊的模板语言 -- {{ 变量名 }} def func(request): return render(request, "index.html", {'current_user': "alex"}) index.html <html> .. <body> <div>{{current_user}}</div> </body> </html> ====> 最后生成的字符串 <html> .. <body> <div>alex</div> </body> </html> -- For循环 def func(request): return render(request, "index.html", {'current_user': "alex", 'user_list': ['alex','eric']}) index.html <html> .. <body> <div>{{current_user}}</div> <ul> {% for row in user_list %} {% if row == "alex" %} <li>{{ row }}</li> {% endif %} {% endfor %} </ul> </body> </html> #####索引################# def func(request): return render(request, "index.html", { 'current_user': "alex", 'user_list': ['alex','eric'], 'user_dict': {'k1': 'v1', 'k2': 'v2'}}) index.html <html> .. <body> <div>{{current_user}}</div> <a> {{ user_list.1 }} </a> <a> {{ user_dict.k1 }} </a> <a> {{ user_dict.k2 }} </a> </body> </html> ###### 条件 def func(request): return render(request, "index.html", { 'current_user': "alex", "age": 18, 'user_list': ['alex','eric'], 'user_dict': {'k1': 'v1', 'k2': 'v2'}}) index.html <html> .. <body> <div>{{current_user}}</div> <a> {{ user_list.1 }} </a> <a> {{ user_dict.k1 }} </a> <a> {{ user_dict.k2 }} </a> {% if age %} <a>有年龄</a> {% if age > 16 %} <a>老男人</a> {% else %} <a>小鲜肉</a> {% endif %} {% else %} <a>无年龄</a> {% endif %} </body> </html> XXOO管理: MySQL SQLAlchemy 主机管理(8列): IP 端口 业务线 ... 用户表: 用户名 密码 功能: 1、 登录 2、主机管理页面 - 查看所有的主机信息(4列) - 增加主机信息(8列) ** 模态对话框 3、查看详细 url: "detail" -> detail def detail(reqeust): nid = request.GET.get("nid") v = select * from tb where id = nid ... 4、删除 del_host -> delete_host def delete_host(request): nid = request.POST.get('nid') delete from tb where id = nid return redirect('/home')
account
View Code
1 def index(): 2 f=open('View/index.html',mode='rb') 3 data=f.read() 4 f.close() 5 return[data,] 6 def login(): 7 return ['login'.encode('utf-8')]
index
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>index</title> 6 </head> 7 <body> 8 <h1>index</h1> 9 </body> 10 </html>
s1.py
View Code
1 import socket 2 def handle_request(client): 3 buf = client.recv(1024) 4 client.send("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8") 5 client.send("Hello Seven") 6 def main(): 7 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 sock.bind(('localhost', 8000)) 9 sock.listen(5) 10 while True: 11 connection, address = sock.accept() 12 handle_request(connection) 13 connection.close() 14 if __name__ == '__main__': 15 main()
s2.py
View Code
1 from wsgiref.simple_server import make_server 2 def RunServer(environ, start_response): 3 # environ 客户端发来的所有数据 4 # start_response 封装要返回给用户的数据,响应头状态 5 start_response('200 OK', [('Content-Type', 'text/html')]) 6 # 返回的内容 7 return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ] 8 if __name__ == '__main__': 9 httpd = make_server('', 8000, RunServer) 10 print("Serving HTTP on port 8000...") 11 httpd.serve_forever()
s3.py
View Code
1 from wsgiref.simple_server import make_server 2 from Controller import account 3 def routers(): 4 urlpatterns = [ 5 (r'/index/',account.index), 6 (r'/login/',account.login), 7 ] 8 return urlpatterns 9 def RunServer(environ, start_response): 10 # environ 客户端发来的所有数据 11 # start_response 封装要返回给用户的数据,响应头状态 12 start_response('200 OK', [('Content-Type', 'text/html')]) 13 url = environ['PATH_INFO'] 14 urlpatterns = routers() 15 func = None 16 for item in urlpatterns: 17 if item[0] == url: 18 func = item[1] 19 break 20 if func: 21 return func() 22 else: 23 return ['404 not found'.encode('utf-8')] 24 if __name__ == '__main__': 25 httpd = make_server('', 8000, RunServer) 26 print("Serving HTTP on port 8000...") 27 httpd.serve_forever()
s3.html
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .c1{ 8 background-color: red; 9 height: 50px; 10 } 11 @media (min-width:900px) { 12 .c2{ 13 background-color: grey; 14 }} 15 </style> 16 </head> 17 <body> 18 <div class="c1 c2"></div> 19 </body> 20 </html>
s4.html
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 .no-radus{ 8 border-radius:0 !important; 9 } 10 </style> 11 <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css"/> 12 <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap-theme.css"/> 13 </head> 14 <body> 15 <a href="#" class="btn btn-primary btn-lg active no-radus" role="button">Primary link</a> 16 <a href="#" class="btn btn-default btn-lg active no-radus" role="button">Link</a> 17 <script src="jquery-1.12.4.js"></script> 18 <script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script> 19 </body> 20 </html>
admin
View Code
1 admin.site.register(models.UserInfo) 2 admin.site.register(models.UserType)
apps
View Code
1 from django.apps import AppConfig 2 class CmdbConfig(AppConfig): 3 name = 'cmdb'
models
View Code
1 from django.db import models 2 # Create your models here. 3 class UserType(models.Model): 4 name = models.CharField(max_length=32) 5 class UserInfo(models.Model): 6 username = models.CharField(max_length=30) 7 pwd = models.CharField(max_length=32) 8 email = models.CharField(max_length=32) 9 user_type = models.ForeignKey(UserType,on_delete=models.CASCADE)
views
View Code
1 from django.shortcuts import render 2 3 # Create your views here. 4 from django.shortcuts import HttpResponse 5 from django.shortcuts import render 6 from django.shortcuts import redirect 7 8 def login(request): 9 # 包含用户提交的所有信息 10 # 获取用户提交方法 11 # print(request.method) 12 error_msg = "" 13 if request.method == "POST": 14 # 获取用户通过POST提交过来的数据 15 user = request.POST.get('user',None) 16 pwd = request.POST.get('pwd',None) 17 if user == 'root' and pwd == "123": 18 # 去跳转到 19 return redirect('/login') 20 else: 21 # 用户密码不配 22 error_msg = "用户名或密码错误" 23 return render(request,'login.html', {'error_msg': error_msg}) 24 25 USER_LIST = [ 26 {'id': 1, 'username': 'alex', 'email': 'asdfasdf', "gender": '男'}, 27 {'id': 2, 'username': 'eriuc', 'email': 'asdfasdf', "gender": '男'}, 28 {"id": 3,'username': 'seven', 'email': 'asdfasdf', "gender": '男'}, 29 ] 30 def home(request): 31 print(request.GET.get('nid')) 32 if request.method == "POST": 33 # 获取用户提交的数据 POST请求中 34 u = request.POST.get('username') 35 e = request.POST.get('email') 36 g = request.POST.get('gender') 37 temp = {'username': u, 'email': e, "gender": g} 38 USER_LIST.append(temp) 39 return render(request, 'test/home.html', {'user_list': USER_LIST}) 40 # def login(request): 41 # # string = """ 42 # # <form> 43 # # <input type='text' /> 44 # # </form> 45 # # 46 # # """ 47 # # f = open('templates/login.html', 'r', encoding='utf-8') 48 # # data = f.read() 49 # # f.close() 50 # # return HttpResponse(data) 51 # return render(request,'login.html') 52 53 # def home(request): 54 # return HttpResponse('<h1>CMDB</h1>') 55 56 # 主机管理 57 # 防火墙 58 # 。。。
settings
View Code
1 """ 2 Django settings for jdjango project. 3 4 Generated by 'django-admin startproject' using Django 1.10.4. 5 6 For more information on this file, see 7 https://docs.djangoproject.com/en/1.10/topics/settings/ 8 9 For the full list of settings and their values, see 10 https://docs.djangoproject.com/en/1.10/ref/settings/ 11 """ 12 13 import os 14 15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) 16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 17 18 19 # Quick-start development settings - unsuitable for production 20 # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ 21 22 # SECURITY WARNING: keep the secret key used in production secret! 23 SECRET_KEY = 'hut(bs^o50n^opj8yneen_sh)m0uvu#sdzr%&eq1x)5p*(tqcz' 24 25 # SECURITY WARNING: don't run with debug turned on in production! 26 DEBUG = True 27 28 ALLOWED_HOSTS = [] 29 30 31 # Application definition 32 33 INSTALLED_APPS = [ 34 'django.contrib.admin', 35 'django.contrib.auth', 36 'django.contrib.contenttypes', 37 'django.contrib.sessions', 38 'django.contrib.messages', 39 'django.contrib.staticfiles', 40 'cmdb', 41 ] 42 43 MIDDLEWARE = [ 44 'django.middleware.security.SecurityMiddleware', 45 'django.contrib.sessions.middleware.SessionMiddleware', 46 'django.middleware.common.CommonMiddleware', 47 #'django.middleware.csrf.CsrfViewMiddleware', 48 'django.contrib.auth.middleware.AuthenticationMiddleware', 49 'django.contrib.messages.middleware.MessageMiddleware', 50 'django.middleware.clickjacking.XFrameOptionsMiddleware', 51 ] 52 53 ROOT_URLCONF = 'jdjango.urls' 54 55 TEMPLATES = [ 56 { 57 'BACKEND': 'django.template.backends.django.DjangoTemplates', 58 'DIRS': [os.path.join(BASE_DIR, 'templates')], 59 'APP_DIRS': True, 60 'OPTIONS': { 61 'context_processors': [ 62 'django.template.context_processors.debug', 63 'django.template.context_processors.request', 64 'django.contrib.auth.context_processors.auth', 65 'django.contrib.messages.context_processors.messages', 66 ], 67 }, 68 }, 69 ] 70 71 WSGI_APPLICATION = 'jdjango.wsgi.application' 72 73 74 # Database 75 # https://docs.djangoproject.com/en/1.10/ref/settings/#databases 76 77 DATABASES = { 78 'default': { 79 'ENGINE': 'django.db.backends.sqlite3', 80 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), 81 } 82 } 83 84 85 # Password validation 86 # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators 87 88 AUTH_PASSWORD_VALIDATORS = [ 89 { 90 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', 91 }, 92 { 93 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', 94 }, 95 { 96 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', 97 }, 98 { 99 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', 100 }, 101 ] 102 103 104 # Internationalization 105 # https://docs.djangoproject.com/en/1.10/topics/i18n/ 106 107 LANGUAGE_CODE = 'en-us' 108 109 TIME_ZONE = 'UTC' 110 111 USE_I18N = True 112 113 USE_L10N = True 114 115 USE_TZ = True 116 117 118 # Static files (CSS, JavaScript, Images) 119 # https://docs.djangoproject.com/en/1.10/howto/static-files/ 120 121 STATIC_URL = '/static/' 122 123 STATICFILES_DIRS = ( 124 os.path.join(BASE_DIR, 'static'), #不加逗号报错 125 ) 126 127 # APPEND_SLASH=True
urls
View Code
1 """jdjango URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/1.10/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.conf.urls import url, include 14 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) 15 """ 16 from django.conf.urls import url 17 from django.contrib import admin 18 from cmdb import views 19 urlpatterns = [ 20 url(r'^admin/', admin.site.urls), 21 # url(r'^h.html/', views.home), 22 url(r'^login', views.login), 23 url(r'^home', views.home), 24 ]
wsgi
View Code
1 """ 2 WSGI config for jdjango project. 3 4 It exposes the WSGI callable as a module-level variable named ``application``. 5 6 For more information on this file, see 7 https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ 8 """ 9 10 import os 11 12 from django.core.wsgi import get_wsgi_application 13 14 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jdjango.settings") 15 16 application = get_wsgi_application()
home
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body style="margin: 0"> 8 <div style="height: 48px;background-color: #dddddd"></div> 9 <div> 10 <form action="/home" method="post"> 11 <input type="text" name="username" placeholder="用户名" /> 12 <input type="text" name="email" placeholder="邮箱"/> 13 <input type="text" name="gender" placeholder="性别"/> 14 <input type="submit" value="添加" /> 15 </form> 16 </div> 17 <div> 18 <table> 19 {% for row in user_list %} 20 <tr> 21 <td>{{ row.username }}</td> 22 <td>{{ row.gender }}</td> 23 <td>{{ row.email }}</td> 24 <td> 25 <a href="/detail?nid={{ row.id }}">查看详细</a> | 26 <a class="del" href="#" row-id="{{ row.id }}">删除</a> 27 </td> 28 </tr> 29 {% endfor %} 30 </table> 31 </div> 32 $('.del').click(function(){ 33 var row_id = $(this).attr('row-id'); 34 $('#nid').val(row_id); 35 }) 36 <div> 37 <form action="/del_host" method="post"> 38 <input style="display: none" id="nid" type="text" name="nid" /> 39 <p> 40 <input type="submit" /> 41 <input type="botton" /> 42 </p> 43 </form> 44 </div> 45 </body> 46 </html>
login
View Code
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <link rel="stylesheet" href="/static/commons.css" /> 7 <style> 8 label{ 9 width: 80px; 10 text-align: right; 11 display: inline-block; 12 } 13 </style> 14 </head> 15 <body> 16 <form action="/login" method="post"> 17 <p> 18 <label for="username">用户名:</label> 19 <input id="username" name="user" type="text" /> 20 </p> 21 <p> 22 <label for="password">密码:</label> 23 <input id="password" name="pwd" type="password" /> 24 <input type="submit" value="提交" /> 25 <span style="color: red;">{{ error_msg }}</span> 26 </p> 27 </form> 28 <script src="/static/jquery.min.js"></script> 29 </body> 30 </html>
manage
View Code
1 #!/usr/bin/env python 2 import os 3 import sys 4 5 if __name__ == "__main__": 6 os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jdjango.settings") 7 try: 8 from django.core.management import execute_from_command_line 9 except ImportError: 10 # The above import may fail for some other reason. Ensure that the 11 # issue is really that Django is missing to avoid masking other 12 # exceptions on Python 2. 13 try: 14 import django 15 except ImportError: 16 raise ImportError( 17 "Couldn't import Django. Are you sure it's installed and " 18 "available on your PYTHONPATH environment variable? Did you " 19 "forget to activate a virtual environment?" 20 ) 21 raise 22 execute_from_command_line(sys.argv)