文章目录
- Prelogue
- 一.前端:
- 1.Html
- 2.Css
- 3.Javasctipt
- 3.1 引入 js
- 3.2 常见类型和操作
- 2.dataset
- 3.节点操作 node->更好的选择节点
- 4.创建元素
- 5.DOM 核心 增删改查
- 6.高级事件:
- BOM
- 5.同步与异步
- 6.location:url
- 7.navaigator:userAgent
- 8.History
- 9.offset 偏移量
- 10.client
- 11.立即执行函数:
- 12.Scroll
- 13.mouseover||mouseenter
- 20.移动端:
- 21.本地存储
- 22.js 闭包
- 23.变量提升 var 才有
- 24.动态参数 arguments 伪数组不能用数组方法
- 25.剩余参数 ... 真数组
- 26. ...arr 展开数组
- 27.=>函数
- 28.数组结构
- 29.对象结构:
- 30.forEach
- 31.构造函数
- 32.静态/动态成员:
- 33.包装类型/引用类型
- 34.原型
- 35.原型添加数组函数:
- 36.constructor
- 37.**proto**
- 38.原型继承
- 39.原型链
- 40.deepcopy
- 41.try/catch
- 42.this call bind apply
- 43.Debunce
- 44.Throttle 节流
- 4.jquery
- 5.python tempalte
- 二.后端
- 三 .数据库
- 四.开发框架
- 五.web 通识
Prelogue
Before this guide,you should konw what is a fullstack in CS.
FULLSTACK in CS means the developer to create a crust of applications or creations by your own;
A full-stack developer helps build and maintain both the front-end and the back-end of a website.
Learn about full-stack developer skills, salary, and how you can become one
fullstack content
Develop and maintain web services and interfaces
Contribute to front-end and back-end development processes
Build new product features or APIs
Perform tests, troubleshoot software, and fix bugs
Collaborate with other departments on projects and sprints
Remember,being a FULLSTACK-DEVELOPER is a rage and trending;
So let’s start
framwork
front
React
Vue
Angular
Svelte
AIpine
Preact
LitElement
Stimulus
Ember
Semantic UI
Jquery
backend
面向Java开发人员的Spring框架+Spring Boot
面向Python开发人员的Django
面向JavaScript开发人员的Express.js
面向.Net 开发者的http://ASP.NET core
面向PHP程序员的Laravel
面向Golang开发者的Fiber 框架
Python -> Flask...
Advice
Choose one your favorite programing language and steaming framework then start.
一.前端:
1.Html
1.1 常见标签
- div / span / a / img / table / form / ul / ol / li / strong / b / i / p /
- 行内:span / a / b / s / del / em / sup /sub /
- 块级:div / p / h1 / table / tr /th / td / ul /ol / li / dl /
- inline-block:img / button / input / lable / select / option /
1.2 input
<input type="text" />
<input type="number" />
<input type="password" />
<input type="radio" name="" /> //单选框name要一致 <input type="button" /> //按钮
<input type="checkbox" /> //多选框
<input type="email" />
<input type="submit" />
2.Css
2.1 常见样式
color:#...;//文本颜色
background-color;
line-height;
box-shadow;
font-family;
font-size;
font-weight;//字体粗细
text-align;
text-indent;//首行文本缩进
text-decoration:none;
//float:
clearfix,clearboth;
//伪类
a:link / visited / hover /active
//position: fixed / absolute /
z-index
2.2 引入 css
<link style="stylesheet" href="" />
2.3 Flex 布局
https://www.bing.com/ck/a?!&&p=ea9889beb2639632JmltdHM9MTcxMjM2MTYwMCZpZ3VpZD0xNWNmODg4MC01ZDFmLTYxMDctM2I1Yy05YjdiNWM3OTYwMDAmaW5zaWQ9NTE5OA&ptn=3&ver=2&hsh=3&fclid=15cf8880-5d1f-6107-3b5c-9b7b5c796000&psq=flex&u=a1aHR0cHM6Ly9mbGV4LmNvbS8&ntb=1
3.Javasctipt
3.1 引入 js
<script></script>
3.2 常见类型和操作
//1.字符串:
var name='hello'
var name=String('hello')
//常见操作
var v1=name.length;
var v2=name[0]//charAt(0)
var v3=name.trim()//'hello'
var v4=name.substring(1,2);//e
// 2.Array:
var a=[11,22];
//常见操作
// --加
a[0]='hello';
a.push('hello');//[11,22,'hello']
a.unshift('a');//['a',11,22]
a.splice(索引位置,0,元素);//0加,1减;
a.splice(1,0,'a');//[11,'a',22]
// --减
a.pop()
a.shift()
a.splice(2,1)//[11]
//循环
for(var item in a){
data=a[item]//11,22
}
// 3.dom创建:
var a=[11,22,33];
for(var idx in a){
var text = a [idx];
var tag=document.createElement('li');
tag.innerText=text;
var parentTag=document.gerElementById('numlist');
parenTag.appendChild(tag);
}
// 4.Dict字典(对象)
info={
name:"Alex",
age:11
}
delete info.age
for(var key in info){
data=info[key]
}
// 5.函数:
function f(){
...
}
(f(){
dosomething();
});
// 6.DOM:
var tag=window.document.getElementById('xx');
tag.innerText="hello"
/html
<input type='text' id='a'>
/js: var txt=document.getElementById('a');
var input=txt.value;
if(input.length>0)
{
var tag=window.document.getElementById('xx');
tag.innerText=input;
var parentTag=document.gerElementById('numlist');
parenTag.appendChild(tag);
input.value='';//clear the content;
}
else
{
alert('input none');
}
2.dataset
element.dataset.index;
element.dataset.listName; //data-list-name;
dataset["index"];
3.节点操作 node->更好的选择节点
// nodeType,nodeName,nodeValue
node.parentNode;
parentNode.childNodes; //包括文本text 不提倡 nodeType==1 -> element
parentNode.children; //推荐
parentNode.firstChild; //第一个节点,可能是文本节点
parentNode.firstElementChild; //第一个元素 E9才有
parent.children[0];
parentNode.lastChild;
parent.children[parent.children.length - 1];
node.nextSibling; //包含text..
node.previousSibling;
node.nextElementSibling; //下一个兄弟元素节点 兼容性
node.previousElementSibling; //上一个兄弟元素节点 nodeType===1为元素节点
创建节点;
document.createElement("tagName");
先创建在添加节点
:node.appendChild(child);//push
:node.insertBefore(child,element);
删除节点:
node.removeChild(child);
复制节点:
node.cloneNode();//再插入,appendchild,insert; 括号为空||false为浅拷贝只拷贝节点不拷贝内容;
node.cloneNode(ture)
4.创建元素
document.write(); //重绘 不推荐
window.load = function () {
xxx;
};
innnerHtml; //字符拼接 用数组可提高效率
createElement; //创建很多个时,快
5.DOM 核心 增删改查
appenchild(child);
createelement("d");
removechild;
src, type, style;
getelementbyid;
getelementbyclassname;
getelementbytagname;
queryselector;
queryselectorall;
6.高级事件:
pageshow
e.persisted//true来自缓存
1.注册事件:
传统:
<button onclick='alert("hi")'></button>
btn.onclick=function(){}
监听://推荐
eventTarget.addEventListener(type,listener[,useCapture])//typeof type -> string ;usecapture=true为捕获阶段
attachEvent()//不推荐
2.删除事件
传统.onclick = null
.removeEventListener("click", fn)
.detachEvent("onclick", fn);
3.dom 事件流 :捕获,目标,冒泡
js 中只能有捕获或者冒泡阶段
onclick,attchEvent 只能捕获冒泡
onblur,onfoucus,onmouseenter.onmouseleave 没有冒泡
4.事件对象
div.onclick = function (event) {
console.log(event || window.event);
};
e.target || window.event.srcElement; //触发事件的对象
this; //绑定的对象
e.currentTarget; //ie678
e.type;
5.阻止默认行为:
e.preventDefault();
兼容:e.returnValue;
return false;
6.防止冒泡:
e.stopPropagation
::e.cancelBuble=true
7.委托事件:
给父类添加事件监听器,点击子类冒泡到父类
e.target.style...
8.Mouse:
docu.addEventListener("contextmenu", function (e) {
e.preventDefault();
});
selectstart;
mousemove;
e.clientX;
e.clientY;
e.pageX;
e.pageY;
e.screenX;
9.keyEvent:
onkeyup / down / press;
up / down不区分大小写;
press区分但不识别功能键;
keyCode;
BOM
兼容性差
全局对象
1.window.onload(fn);以最后一个为准
2.window.add-L(‘DOMContentLoaded’,fn);
3.window.(on)resize w.innerWidth;//当前屏幕宽度
4.定时器:
setTimeout //只执行一次
setTimeout(callback, 2000); //延迟事件毫秒;default:0
setTimeout("fn()", 2000); //不推荐
起名字:
var timer1=setTimeout(fn,2000);
stop:
window.clearTimeout(timer1)
setInterval(callback,[s]);//不断调用
clearInterval(timer);
this 谁调用指向谁
5.同步与异步
js 是单线程
console.log(1);
setTimeout(function () {
console.log(3);
}, 1000);
console.log(2);
//r:1,2,3
1.回调函数属于异步任务->任务队列
2.同步任务->主线程执行栈
3.js 代码执行流程:event loop
先同步再异步
先执行栈再执行队列
栈执行完后 队列=true则将任务队列放到执行栈后面执行
example
console.log(1);
setTimeout(function () {
console.log("end");
}, 0);
console.log(2);
6.location:url
url:protocol://host[:port]/path/ [?query] #fragment
| | | | |
location.href||host||port||pathname||search||hash||
l.assign();
l.replace();
l.reload([true]);
7.navaigator:userAgent
if (
navigator.userAgent.match(
/phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrower|JUC|Feenec|wOSBrower|BrowerNG|WebOS|Symbian|Windows Phone)/i
)
) {
windows.location.href = ""; //mobile
} else {
widows.location.href = ""; //pc
}
8.History
history.back();
history.forword();
history.go(1 | 2 | -1);
9.offset 偏移量
element.offsetParent;//return a fatherelement having a position
.offsetTop;
.offsetLeft;// 有无定位
.offsetWidth;//padding+border+margin; only_read
.offsetHeight;//no 单位
style 更适合修改值 //只能读取行内元素
offset 更适合读取值
10.client
element.clientTop; //上边框
.clientLeft
.clientWidth
.clientHeight//不含边框,不带单位
11.立即执行函数:
优势:独立创建了一个作用域
1(function () {})();
2((function () {})());
12.Scroll
element.scrollTop; //返回被卷去的上侧距离,不带单位
element.scrollLeft;
element.scrollWidth; //返回实际高度,不含边框
div.add - L("scroll", fn);
window.pageYOffset
13.mouseover||mouseenter
mouseover 子盒子也会触发
mouseenter 不会冒泡,只会触发自己的盒子
20.移动端:
1. touch
touchend
touchmove
touchstart
2.touchevent
touches/targetTouches/changedTouches
21.本地存储
localstorage/sessionstorage
.setItem/.getItem/.clear()/removeItem(…)
22.js 闭包
<script>
function outer() {
let a = 1;
function fn() {
console.log(a);
}
return fn;
}
const f = outer();
//application
function cnt(){
let i=0;
function fn(){
i++;
console.log(i);
}
return fn;
}
let count=cnt();
count();
</script>
23.变量提升 var 才有
<script>
//只提升声明,当前作用下 console.log(num + 'jj');//undefinedjj var num = 33;
</script>
函数也有提升,只提升声明,不调用;
24.动态参数 arguments 伪数组不能用数组方法
function sum(e) {
let s = 0;
for (let index = 0; index < arguments.length; index++) {
s += arguments[index];
}
return s;
}
console.log(sum(1, 2));
console.log(sum(1, 2, 3, 4));
25.剩余参数 … 真数组
<script>
function sum(...arr) {
let s=0;
arr.forEach(function(a){
s+=a;
})
return s;
}
console.log(sum(1,2));
console.log(sum(1,2,3,4));
</script>
26. …arr 展开数组
let arr1 = [1, 3, 4, 5, 6, 7];
let arr2 = [1, 3, 4, 5, 6, 7];
// ...arr1 === 1,3,5...
console.log(Math.max(...arr1));
console.log(Math.min(...arr2));
let arr = [...arr1, ...arr2];
27.=>函数
<script>
let fn=name=>({
name:name
})
console.log(fn('Alex'));//name:Alex
</script>
let sum = (...arr) => {
let s = 0;
arr.forEach((x) => (s += x));
return s;
};
console.log(sum(1, 2));
28.数组结构
let a = 1;
let b = 2;
[a, b] = [b, a]; //a:2,b:1;
let [a = 0, b = 0] = [1, [2, 4]];
console.log(a);
console.log(b);
console.log(b[0]);
let [a2 = 0, [c, d]] = [1, [2, 4]];
console.log(c);
console.log(d);
let getvalue = () => [22, 55];
let [val1, val2] = getvalue();
console.log(val1);
29.对象结构:
const pig = {
name: "Aelx",
age: 3,
};
const { name: pigname, age } = pig;
console.log(pigname);
console.log(age);
const goods = [
{
goodsName: "huawei",
price: 1333,
manager: {
age: 33,
address: "beijing",
},
},
];
const [{ goodsName, price }] = goods;
console.log(goodsName);
console.log(price);
const [
{
manager: { age: myAge, address },
},
] = goods;
console.log(address);
function a({ data: myData }) {
return myData.xxx();
}
30.forEach
let arr = [1, 3, "red"];
arr.forEach(function (item, index) {
console.log(item);
console.log(index);
});
31.构造函数
//构造函数
// 1.首字母大写 2.无return 3.new为实例化返回一个对象
function Goods(name, price, count) {
this.name = name;
this.price = price;
this.count = count;
}
const { name, price, count } = new Goods("xiaomi", "1999", 20);
console.log(name);
console.log(price);
console.log(count);
32.静态/动态成员:
function Person(name, age) {
(this.name = name), (this.age = age);
//实例成员
}
const xm = new Person("xiaoming", 33);
console.log(xm.name); //实例属性
xm.sayHi = () => {
console.log("xiaomign Hello");
}; //实例方法
Person.canwalk = true; //静态属性
Person.sayBye = () => {
console.log("byebye");
}; //静态方法
Person.sayBye();
console.log(Person.canwalk);
33.包装类型/引用类型
1.Object
let obj = {
name: "Alex",
age: 33,
};
const keys = Object.keys(obj);
const values = Object.values(obj);
console.log(keys);
console.log(values);
const obj2 = {};
Object.assign(obj2, obj);
console.log(obj2);
2.Array
Array 创建
let arr = new Array(1);
let arr2 = new Array(3);
console.log(arr); //[空]
console.log(arr.length); //1
console.log(arr[0]); //undefined
console.log(arr[1]); //undefined
console.log(arr2); //[空x3]
console.log(arr2.length); //3
1.reduce
const arr = [1, 2, 3];
let sum = arr.reduce((prev, current) => prev + current, 10);
console.log(sum);
const arr2 = [
{
name: "zhangsan",
salary: 1000,
},
{
name: "lisi",
salary: 333,
},
{
name: "wangwu",
salary: 222,
},
];
arr2.reduce((prev, current) => {
return prev + current.salary;
}, 0); //第三个参数不为零则默认数组第一个元素
2.from(arr);
let lis = document.querySelectorAll("ul li"); //NodeList 伪数组
console.log(lis);
let li = Array.from(lis); //转Array
console.log(li);
li.pop();
console.log(li);
3.find(item=>item…)
let arr = [10, 20, 30];
let a = arr.find((item) => item > 10);
console.log(a); //20
let obj = [
{
name: "xiaomi",
price: 3333,
},
{
name: "huawei",
price: 9999,
},
];
let huaweiObj = obj.find((item) => item.name === "huawei");
console.log(huaweiObj); //{name: 'huawei',price: 9999}
4.at(-1)
34.原型
//公共属性写在构造函数里
//公共方法写在原型里
function Person(name, age) {
(this.name = name), (this.age = age);
//this 指向实例化对象
}
Person.prototype.sing = function () {
//this 指向实例化对象
console.log("singing...");
};
let ldh = new Person("liudehua", 33);
ldh.sing();
35.原型添加数组函数:
const arr = [1, 2, 3];
Array.prototype.min = function (arr) {
return Math.min(...this);
};
Array.prototype.max = function (arr) {
return Math.max(...this);
};
Array.prototype.sum = function (arr) {
return this.reduce((prev, current) => prev + current, 0);
};
console.log(arr.min());
console.log(arr.max());
console.log(arr.sum());
36.constructor
function Person(name, age) {
(this.name = name), (this.age = age);
}
console.log(Person.prototype);
Person.prototype = {
constructor: Person,
sing: function () {
console.log("sing");
},
dance: function () {
console.log(dance);
},
};
console.log(Person.prototype.constructor === Person);
37.proto
function Person(name, age) {
(this.name = name), (this.age = age);
}
const xm = new Person("xm", 33);
//__proto__ -> [[Prototype]] js非标准属性
console.log(xm.__proto__ === Person.prototype);
console.log(xm.constrctor === Person);
38.原型继承
function Person() {
(this.eyes = 2), (this.head = 1);
}
function Woman() {}
Woman.prototype = new Person();
Woman.prototype.sing = function () {
console.log("sing");
};
let woman = new Woman();
woman.sing();
function Man() {}
Man.prototype = new Person();
// Man.prototype.sing = function () {
// console.log('sing');
// }
let man = new Man();
man.sing;
39.原型链
//原型链
//只要是对象就有__proto__,只要是原型就有constructor
function Person() {
(this.eyes = 2), (this.head = 1);
}
let p1 = new Person();
console.log(p1.eyes);
console.log(p1.__proto__);
console.log(Person.prototype);
console.log(Person.prototype.__proto__);
console.log(Person.prototype.__proto__ === Object.prototype);
console.log(Object.prototype.__proto__ === null);
console.log(Person instanceof Object);
40.deepcopy
//deepcopy copy
let obj1 = {
name: "Alex",
hobby: [1, "sing"],
family: {
father: "Mith",
},
};
let obj2 = obj1;
//共同用一个地址,你改变了他也改变,浅拷贝
console.log(obj2);
obj2.hobby[1] = "Obj2";
console.log(obj2);
console.log(obj1);
// deepcopy三种实现:1.自定义递归函数deepcp,2.loadlash:_.cloneDeep(obj),3.JSON.stringify
// function deepCopy(newObj,oldObj){
// if()
// }
let newobj = JSON.parse(JSON.stringify(obj1));
41.try/catch
let arr = [];
try {
let div = document.querySelector(".div");
function a() {}
} catch (error) {
debugger;
throw new Error("Error");
} finally {
console.log("finally");
}
console.log("after try");
42.this call bind apply
//this:call,apply,bind
//fn.call(thisArg,args*)
//fn.apply(thisArg,[Array])
//fn.bind(thisArg,args*) 不调用 return fn(this不同)
console.log(this); //window
function fn(x, y) {
console.log(this);
return x + y;
}
fn(); //window
const obj = {
name: "Alex",
};
let a = fn.call(obj, 1, 2); //log
console.log(a); //3
let b = fn.apply(obj, [1, 3]);
console.log(b); //4
let c = fn.bind(obj, 3, 5);
console.log(c);
console.log(c(4, 6)); //8
let d = fn.bind(obj);
console.log(c(4, 6)); //10
43.Debunce
44.Throttle 节流
4.jquery
$( # id) $(.class) $(‘h1’)
// 1.直接找
<p>lll</p>;
$("#test").text("hello");
$('.c1 .c2 a')
$('#id1,#id2')//多选择器
$('input[name='n1']')
// 2.间接寻找
$('#id1').perv()/next().next()/.../siblings()../
.parent()/.children()/.children('.class1')/
find('div').removeClass('hello')
// 3.样式:
addClass
removeClass
hasClass
remove()
// 4.值的操作
$("#test").text("hello");
/html:
$('#input').val()
$('#input').val("hahahh")//
5.创建标签$('<li>')
// 5.事件绑定
$('li').click(function(){
var text=$(this).text();//点这个标签
...
})
当页面框架加载完成在执行:
$(function(){
$('li').click(function(){
var text=$(this).text();//点这个标签
...
})
...
})
5.python tempalte
> {{item}}
> {% for item in data_list %}
二.后端
1.Python
1.1.编码:
> ascll,gb2312(中文两个字节),unicode(ucs2/ucs4),utf-8(中文三个字节)
> 单位:
> 位/字节/kb/m/g/t;
1.2.Python 字符串的格式化:
var a="hello my name is {},come from us,{}".fomat("Alexmaodali","SanfSco);
var a="hello my name is%s,old:%d;"%("Alexmaodali",33);
1.3.DataType
int bool str list tuple dict set float None
False:None,空,0
可变:list,set,dict
字典的key和集合元素,必须是可哈希的DataType;
不可哈希:list,set,dict
1.4.独有功能:
共有:len/index/切片/for/是否包含/join
-str:upper/lower/startwith,split/strip..
-list:append/insert/remove/pop...
-dict:get/keys/items/values...
1.5.推导式
data=[i for i in range(10) if i < 5]
1.6.函数:
动态参数:*args,**kwargs;
无参数默认返回None
全局变量一般大写
局部变量小写下划线连接/global引用全局变量而不是局部变量;
1.内置函数
bin/hex/odc/max/open/divmod/sorted
2.文件操作
with open ...
-r/rb
-w/wb写(清空)/自动新建文件
-a/ab/追加/自动新建文件
文件夹不存在,报错
Address Above:
os.makedirs/os.path.exsits
1.7.module
build-in-:time/datatime/json/re/random/os...
source:requests/openpyxl/bs4/flask/python-docx
self-build:os.path
1.查看文件:
os.listdir/os.walk
2.time
3.JSON:
无单引号/元组
序列化:JSON.dumps
4.re:
-\d \w
re.search/re.match/re.findall
贪婪,不贪婪加?
5.
pip
wheel
源码
1.8.oop
封装,继承,多态
OO 语言之父 Alan Kay,Smalltalk 的发明人,在谈到 OOP 时是这样说的:
I thought of objects being like biological cells and/or individual computers on a network, only able to communicate with messages (so messaging came at the very beginning -- it took a while to see how to do messaging in a programming language efficiently enough to be useful)....OOP to me means only messaging, local retention and protection and hiding of state-process, and extreme late-binding of all things. It can be done in Smalltalk and in LISP.
OOP Concepts
Class
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
2.java
三 .数据库
1.Mysql(管理员打开 cmd)
synax:
create table admin(
id int not null auto_increment primary key,
username varchar(16) not null,
password varchar(16) not null,
phone char(11) not null
) default charset=utf8;
1.1.Start services:
临时启动:
mysqld.exe
服务启动:
“D:\WorkingAbout\FrontedTools\MySQL\mysql-5.7.31-winx64\bin\mysqld.exe” --install mysql57
net start mysql57
net stop mysql57
“D:\WorkingAbout\FrontedTools\MySQL\mysql-5.7.31-winx64\bin\mysqld.exe” -h 127.0.0.1 -P 3306 -u -root -p
加入环境变量:
mysql -u root -p
1.2.set password=password(“root”)
1.3.exit;
2.pymysql
新增,删除,修改一定要 connect.commit(),不然数据库没数据
2.1.插入 insert
import pymysql
if __name__ == '__main__':
# 1.连接数据库
con = pymysql.connect(host="localhost", port=3306,
user='root', passwd='root', charset='utf8', db='unicom')
cursor = con.cursor(cursor=pymysql.cursors.DictCursor)
#2.执行SQL指令;
sql = "insert into admin(username,password,mobile) values(...)"
cursor.execute(sql)
con.commit()
#3.关闭连接;
cursor.close()
con.close()
2.2.选择 select
import pymysql
if __name__ == '__main__':
# 1.连接数据库
con = pymysql.connect(host="localhost", port=3306,
user='root', passwd='root', charset='utf8', db='unicom')
cursor = con.cursor(cursor=pymysql.cursors.DictCursor)
#2.执行SQL指令;
sql = "select * from admin where id > %s"
cursor.execute(sql,[2,])
# con.commit()
# fetchone()
data_list=cursor.fetchall()
#3.关闭连接;
cursor.close()
con.close()
2.3.格式分组
sql = "insert into admin(username,password,mobile) values(%(n1)s,%(n2)s,%(n3)s)"
cursor.execute(sql, {"n1": 'hello', "n2": "liek", "n3": "3333"})
con.commit()
四.开发框架
1.Flask:
dir:
└─static
├─css
├─img
├─js
│ └─jQuery-3.7
│
├─plugins
│ ├─bootstrap-3.4.1-dist
│
└─templates
|_index.html
|_demo.py
from flask import Flask,render_template
app=Flask(__name__)
@app.route("/add/user")
def add_user():
# //in dir:templates
return render_template("add_user.html")
if __name__=='__main__':
app.run()
2.Django
2.1 安装
pip install django
2.2 创建 django 项目
django-admin startproject 项目名称
2.3 默认文件
mysite
|-- manage.py //项目管理,启动
|-- mysite
|-- __init__.py
|-- settings.py //项目配置文件
|-- urls.py //url和函数对应关系
|-- asgi.py //接收网络请求
|-- wsgi.py //接收网络请求
2.4 创建 app(功能)
python manage.py startapp app 名
2.5 启动 django 项目
2.5.1 注册 app
in INSTALLED_APPS 加 app名.apps.App名Config
2.5.2 设置 urls
urls:
from app名 import views
urlpattern=[
path('index/',views.index),
]
2.5.3 写函数 view.py
from django.shortcuts import render , HttpsResponse
def index(request):
return HttpsResponse("启动成功")
2.5.4 启动
python manage.py runserver
localhost/index/
2.6 templates and static
render(request,‘index.html’)
2.6.1 templates 查找规则
默认去 app 名目录下的 templates 找(app 注册顺序)
> TEMPLATES=[
> 'DIRS':[os.path.join(BASE_DIR,'templates')],
> ]
上面存在则优先根目录[提前配置]
2.6.2 static 静态文件
> app名 / static
> static / css , js , plugins , img ...
静态文件写法
//load 这一行不要写在html最上面 //运行时要运行django项目而不是html文件 {% load
static %} <link rel="stylesheet" href="{% static 'plugins/...css' %}" />
2.7 模板语法
取列表:
{{ n1.0/1 ... }}
render(request,'tpl.html',{"n1":name,"n2":data_list})
{% for item(k,v) in n2(.keys,.values) %}
<span>{{ item }}</span>
{% endfor %}
{% if n1 == "name" %}
...html...
{% elif n1 =="xxx" %}
...html...
def user_info(request):
data_list=UserInfo.objects.all()
return render(request,"user_info.html",{"data_list":data_list})
2.8 请求与响应
1.request请求:
-request.method
-request.GET 获取在url上传递值
-request.POST
2.HttpsResponse返回/响应
-1.HttpsResponse("xxx")
-2.读取html内容+渲染templates-->字符串,返回给浏览器用户:
-return render(request,'index.html',{"title":"ddd"})
-3重定向
return redirect("baudu.com")
e.g:
if request.method=="GET":
xxx;
if request.method=="POST":
username=request.POST.get("user",None)
#获取checkbox等多内容
username=request.POST.getlist("user",None)
<form xxx>
{% csrf_token %}
</form>
view.py:
from django.template.context_processors import csrf
......
2.9 django 连接 mysql
> pip install mysqlclient(2.2.0)
2.9.1 orm 创建数据库
mysql:
create table admin(
id int not null auto_increment primary key,
username varchar(16) not null,
password varchar(16) not null,
phone char(11) not null
) default charset=utf8;
create table user(
id int not null auto_increment primary key,
username varchar(255) not null,
password varchar(255) not null,
) default charset=utf8;
orm:对表操作,但创建不了数据库
创建数据库:
create database databasename DEFAULT CHARSET utf8 COLLATE utf8_general_ci;
django/settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
#数据库名字
'NAME':'dbname',
'USER': 'root',
'PASSWORD': 'xxx',
'HOST': 'localhost',
'PORT': 3306,
}
}
2.9.2 django 操作表
models.py:
from django.db import models
# Create your models here.
class UserInfo(models.Model):
name=models.CharField(max_length=32)
password=models.CharField(max_length=32)
age=models.IntegerField()
"""
create table app名_类名小写
create table appapp01_userinfo(
id bigint auto_increment primary key,
name varchar(32),
password varchar(32),
);
"""
2.9.3 更新数据库表:
python manage.py makemigrations
python manage.py migrate
2.9.4 添加字段(列)
class UserInfo(models.Model):
"""用户表"""
name = models.CharField(verbose_name="用户名", max_length=32)
password = models.CharField(max_length=32)
age = models.IntegerField()
age=models.IntegerField(default=2)
age1=models.IntegerField(null=True,blank=True)
对表结构进行操作只需对 models.py 中的类进行操作,再执行命令
2.9.5 操作表中的数据
2.9.5.1 新增数据(可以写在 view.py 类里)
# 新增数据(可以写在view.py类里)
UserInfo.objects.create(name="alexmaodali",password="sss",age=12)
UserInfo.objects.filter(id=2).delete
UserInfo.objects.all().delete
#获取数据
data_list=UserInfo.objects.all()#queryset(list)
for obj in data_list:
print(obj.id,obj.name)
#获取一行
row_obj=UserInfo.objects.filter(id=2).first()
#更新数据
UserInfo.objects.filter(name='ssss').update(name="2222")
2.9.5.2 绑定表/关联表
#自动生成depart_id列
depart=models.ForeignKey(to="Department",to_field="id")
#级联删除
depart=models.ForeignKey(to="Department",to_field="id",on_delete=models.CASCADE)
#置空
depart=models.ForeignKey(to="Department",null=True,blank=True,to_field="id",on_delete=models.SET_NULL)
2.9.5.3 性别
GENDER_CHOICES=(
(1,"男"),
(2,"女"),
)
gender=models.SmallInterger(verbose_name="sex",choices=GENDDER_CHOICES)
for obj in queryset:
obj.get_gender_display()#模板里不加括号
obj.depart.title;#直接获取关联表的对象
2.9.5.4 python 时间 datatime 转字符
obj.create_time.strftime("%Y-%m-%d")
模板里:{{item.event_start|date:"Y-m-d H:i:s"}}
2.10 新建用户 Form and ModelForm
1.原始
2.django 组件:form 组件,modelform 组件
from django import forms
2.10.1 Form
class myform(Form):
user=forms.CharField(widget=forms.Input)#input框插件
pwd=forms.CharField(widget=forms.Input)
email=forms.CharField(widget=forms.Input)
def user_add(request):
if...:
form=myform()
return render(xx,xx,{'form':form})
tempaltes:
{{form.user}}
{{form.pwd}}
...
or: {%for field in form%}
{{field}}
{{field.errors}}
{%endfor%}
2.10.2 ModelForm
from django import forms
class myform(forms.ModelForm):
class Meta:
model=models.UserInfo
fields=["name","password","age"]
def xxx(rq):
form = myform()
return xxx
生成 input 框:
{{form.name}}
#取备注
{{form.name.label}}:{{form.name}}
{%for field in form%}
{{field.label}}:{{field}}
{%endfor%}
对象返回要求的值:
class myform(forms.ModelForm):
class Meta:
model=models.UserInfo
fields=["name","password","age"]
def __str__(self):
return self.title
样式:
widgets={
"name":forms.TextInput(attrs={"class":"form-control"})
}
#
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
for name.foeld in self.fields.items():#name字段名字
field.widget.attrs={"class":"form-control","placeholder":field.label}
校验数据:
form=UserModelForm(data=request.POST)
if form.is_valid():
form.save()#保存到数据库
else:
# print(form.errors)
return render()
zh-hans
替代 placeholder:
row_object = models....first()
form = UserModeForm(instance=row_object)
不新增同一对象:
form=userModelform(data=re.POST,instance=row_object)
新增其他值:
form.instance.字段名 = xxx
2.11 html 继承
{%extends 'layout.html'%}
{%block content自定义名字%}
{%endblock%}
五.web 通识
HTTP URL
http://host[":"port][abs_path]
http 请求由请求行,消息报头,请求正文三部分构成。
HTTP 请求状态行
GET /example.html HTTP/1.1 (CRLF)
HTTP 响应状态行
HTTP/1.1 200 OK (CRLF)
HTTP StatusCode
常见状态代码、状态描述、说明: 200: OK - 客户端请求成功 400: Bad Request - 客户端请求有语法错误,不能被服务器所理解 401: Unauthorized - 请求未经授权,这个状态代码必须和WWW-Authenticate报头域一起使用 403: Forbidden - 服务器收到请求,但是拒绝提供服务 404: Not Found - 请求资源不存在,eg:输入了错误的URL 500: Internal Server Error - 服务器发生不可预期的错误 * 503: Server Unavailable - 服务器当前不能处理客户端的请求,一段时间后,可能恢复正常
HTTP 的不足
通信使用明文(不加密),内容可能会被窃听
不验证通信方的身份,因此有可能遭遇伪装
无法证明报文的完整性,所以有可能已遭篡改
HTTPS
HTTP + 加密 + 认证 + 完整性保护 = HTTPS(HTTP Secure )
JSON
JSON 比 XML 更小、更快,更易解析。
javaScript原生支持JSON,解析速度会很快
XML解析成DOM对象的时候,浏览器【IE和fireFox】会有差异
使用JSON会更简单
json only include array and object
var employees = [
{ firstName: "Bill", lastName: "Gates" },
{ firstName: "George", lastName: "Bush" },
{ firstName: "Thomas", lastName: "Carter" },
];
JSON 解析
https://www.json.cn/