python学习笔记_week18
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')
def index():
f=open('View/index.html',mode='rb')
data=f.read()
f.close()
return[data,]
def login():
return ['login'.encode('utf-8')]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
</head>
<body>
<h1>index</h1>
</body>
</html>
import socket
def handle_request(client):
buf = client.recv(1024)
client.send("HTTP/1.1 200 OK\r\n\r\n",encoding="utf-8")
client.send("Hello Seven")
def main():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('localhost', 8000))
sock.listen(5)
while True:
connection, address = sock.accept()
handle_request(connection)
connection.close()
if __name__ == '__main__':
main()
from wsgiref.simple_server import make_server
def RunServer(environ, start_response):
# environ 客户端发来的所有数据
# start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
# 返回的内容
return [bytes('<h1>Hello, web!</h1>', encoding='utf-8'), ]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
from wsgiref.simple_server import make_server
from Controller import account
def routers():
urlpatterns = [
(r'/index/',account.index),
(r'/login/',account.login),
]
return urlpatterns
def RunServer(environ, start_response):
# environ 客户端发来的所有数据
# start_response 封装要返回给用户的数据,响应头状态
start_response('200 OK', [('Content-Type', 'text/html')])
url = environ['PATH_INFO']
urlpatterns = routers()
func = None
for item in urlpatterns:
if item[0] == url:
func = item[1]
break
if func:
return func()
else:
return ['404 not found'.encode('utf-8')]
if __name__ == '__main__':
httpd = make_server('', 8000, RunServer)
print("Serving HTTP on port 8000...")
httpd.serve_forever()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.c1{
background-color: red;
height: 50px;
}
@media (min-width:900px) {
.c2{
background-color: grey;
}}
</style>
</head>
<body>
<div class="c1 c2"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.no-radus{
border-radius:0 !important;
}
</style>
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css"/>
<link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap-theme.css"/>
</head>
<body>
<a href="#" class="btn btn-primary btn-lg active no-radus" role="button">Primary link</a>
<a href="#" class="btn btn-default btn-lg active no-radus" role="button">Link</a>
<script src="jquery-1.12.4.js"></script>
<script src="bootstrap-3.3.7-dist/js/bootstrap.js"></script>
</body>
</html>
admin.site.register(models.UserInfo)
admin.site.register(models.UserType)
from django.apps import AppConfig
class CmdbConfig(AppConfig):
name = 'cmdb'
from django.db import models
# Create your models here.
class UserType(models.Model):
name = models.CharField(max_length=32)
class UserInfo(models.Model):
username = models.CharField(max_length=30)
pwd = models.CharField(max_length=32)
email = models.CharField(max_length=32)
user_type = models.ForeignKey(UserType,on_delete=models.CASCADE)
from django.shortcuts import render # Create your views here.
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect def login(request):
# 包含用户提交的所有信息
# 获取用户提交方法
# print(request.method)
error_msg = ""
if request.method == "POST":
# 获取用户通过POST提交过来的数据
user = request.POST.get('user',None)
pwd = request.POST.get('pwd',None)
if user == 'root' and pwd == "":
# 去跳转到
return redirect('/login')
else:
# 用户密码不配
error_msg = "用户名或密码错误"
return render(request,'login.html', {'error_msg': error_msg}) USER_LIST = [
{'id': 1, 'username': 'alex', 'email': 'asdfasdf', "gender": '男'},
{'id': 2, 'username': 'eriuc', 'email': 'asdfasdf', "gender": '男'},
{"id": 3,'username': 'seven', 'email': 'asdfasdf', "gender": '男'},
]
def home(request):
print(request.GET.get('nid'))
if request.method == "POST":
# 获取用户提交的数据 POST请求中
u = request.POST.get('username')
e = request.POST.get('email')
g = request.POST.get('gender')
temp = {'username': u, 'email': e, "gender": g}
USER_LIST.append(temp)
return render(request, 'test/home.html', {'user_list': USER_LIST})
# def login(request):
# # string = """
# # <form>
# # <input type='text' />
# # </form>
# #
# # """
# # f = open('templates/login.html', 'r', encoding='utf-8')
# # data = f.read()
# # f.close()
# # return HttpResponse(data)
# return render(request,'login.html') # def home(request):
# return HttpResponse('<h1>CMDB</h1>') # 主机管理
# 防火墙
# 。。。
"""
Django settings for jdjango project. Generated by 'django-admin startproject' using Django 1.10.4. For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
""" import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'hut(bs^o50n^opj8yneen_sh)m0uvu#sdzr%&eq1x)5p*(tqcz' # SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cmdb',
] MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
] ROOT_URLCONF = 'jdjango.urls' 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',
],
},
},
] WSGI_APPLICATION = 'jdjango.wsgi.application' # Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
} # Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
] # Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'), #不加逗号报错
) # APPEND_SLASH=True
"""jdjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from cmdb import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
# url(r'^h.html/', views.home),
url(r'^login', views.login),
url(r'^home', views.home),
]
"""
WSGI config for jdjango project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
""" import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jdjango.settings") application = get_wsgi_application()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body style="margin: 0">
<div style="height: 48px;background-color: #dddddd"></div>
<div>
<form action="/home" method="post">
<input type="text" name="username" placeholder="用户名" />
<input type="text" name="email" placeholder="邮箱"/>
<input type="text" name="gender" placeholder="性别"/>
<input type="submit" value="添加" />
</form>
</div>
<div>
<table>
{% for row in user_list %}
<tr>
<td>{{ row.username }}</td>
<td>{{ row.gender }}</td>
<td>{{ row.email }}</td>
<td>
<a href="/detail?nid={{ row.id }}">查看详细</a> |
<a class="del" href="#" row-id="{{ row.id }}">删除</a>
</td>
</tr>
{% endfor %}
</table>
</div>
$('.del').click(function(){
var row_id = $(this).attr('row-id');
$('#nid').val(row_id);
})
<div>
<form action="/del_host" method="post">
<input style="display: none" id="nid" type="text" name="nid" />
<p>
<input type="submit" />
<input type="botton" />
</p>
</form>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/commons.css" />
<style>
label{
width: 80px;
text-align: right;
display: inline-block;
}
</style>
</head>
<body>
<form action="/login" method="post">
<p>
<label for="username">用户名:</label>
<input id="username" name="user" type="text" />
</p>
<p>
<label for="password">密码:</label>
<input id="password" name="pwd" type="password" />
<input type="submit" value="提交" />
<span style="color: red;">{{ error_msg }}</span>
</p>
</form>
<script src="/static/jquery.min.js"></script>
</body>
</html>
#!/usr/bin/env python
import os
import sys if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "jdjango.settings")
try:
from django.core.management import execute_from_command_line
except ImportError:
# The above import may fail for some other reason. Ensure that the
# issue is really that Django is missing to avoid masking other
# exceptions on Python 2.
try:
import django
except ImportError:
raise 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?"
)
raise
execute_from_command_line(sys.argv)
python学习笔记_week18的更多相关文章
- python学习笔记整理——字典
python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...
- VS2013中Python学习笔记[Django Web的第一个网页]
前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...
- python学习笔记之module && package
个人总结: import module,module就是文件名,导入那个python文件 import package,package就是一个文件夹,导入的文件夹下有一个__init__.py的文件, ...
- python学习笔记(六)文件夹遍历,异常处理
python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...
- python学习笔记--Django入门四 管理站点--二
接上一节 python学习笔记--Django入门四 管理站点 设置字段可选 编辑Book模块在email字段上加上blank=True,指定email字段为可选,代码如下: class Autho ...
- python学习笔记--Django入门0 安装dangjo
经过这几天的折腾,经历了Django的各种报错,翻译的内容虽然不错,但是与实际的版本有差别,会出现各种奇葩的错误.现在终于找到了解决方法:查看英文原版内容:http://djangobook.com/ ...
- python学习笔记(一)元组,序列,字典
python学习笔记(一)元组,序列,字典
- Pythoner | 你像从前一样的Python学习笔记
Pythoner | 你像从前一样的Python学习笔记 Pythoner
- OpenCV之Python学习笔记
OpenCV之Python学习笔记 直都在用Python+OpenCV做一些算法的原型.本来想留下发布一些文章的,可是整理一下就有点无奈了,都是写零散不成系统的小片段.现在看 到一本国外的新书< ...
随机推荐
- 一:elasticsearch常用操作总结
索引 搜索 mapping 分词器 1.创建索引 http://192.168.65.131:9200/smartom_index 2.查看索引: http://192.168.65.131:9200 ...
- Gradle Java Web应用程序并在Tomcat上运行
1- 创建Gradle工程 打开 Eclipse ,在菜单中找到 File -> New -> Other…,在打开界面中选择 Gradle Project,如下图中所示 - 点击下一步( ...
- 细看Thread的 start() 和 run()方法
1.start(): 我们先来看看API中对于该方法的介绍: 使该线程开始执行:Java 虚拟机调用该线程的 run 方法. 结果是两个线程并发地运行:当前线程(从调用返回给 start 方法)和另一 ...
- 【springBoot】之starter pom
SpringBoot针对不同业务提供了不同的starter pom,根据springboot版本不同可能有差异. spring-boot-starter springboot核心starter ,包括 ...
- bzoj5017: [Snoi2017]炸弹
Description 在一条直线上有 N 个炸弹,每个炸弹的坐标是 Xi,爆炸半径是 Ri,当一个炸弹爆炸时,如果另一个炸弹所在位置 Xj 满足: Xi−Ri≤Xj≤Xi+Ri,那么,该炸弹也会被 ...
- JVM异常之:直接内存溢出
示例: package com.dxz.jvm; import java.lang.reflect.Field; import sun.misc.Unsafe; /** * @Described:直接 ...
- 问题 B: 【例9.3】求最长不下降序列(基础dp)
问题 B: [例9.3]求最长不下降序列 时间限制: 1 Sec 内存限制: 128 MB提交: 318 解决: 118[提交][状态][讨论版][命题人:quanxing] 题目描述 设有由n( ...
- JSON 使用
ylbtech-JSON: JSON 使用 1. 把 JSON 文本转换为 JavaScript 对象返回顶部 JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 ...
- 面试总结之PYTHON
source code https://github.com/haoran119/interview/tree/master/interview%20summary%20of%20python [ZZ ...
- 廖雪峰Java2面向对象编程-3继承和多态-1继承
1.继承 继承是一种代码复用的方式. Student与Person有相同部分的代码. Student可以从Person继承,这样Student获得了Person的所有功能,只需要编写新增的功能即可.通 ...