[后端-Flask總結(jié)]-flask學(xué)習(xí)總結(jié)
1.flask開(kāi)發(fā)基礎(chǔ)與入門:
1.1web開(kāi)發(fā)基礎(chǔ)
1.1.1 前端框架:
bootstrap, j-query, angular, react
1.2 flask 路由
from flask import Flask
# 從flask引入request實(shí)例
from flask import request, url_for
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
# 換請(qǐng)求方式
@app.route('/user', methods=['POST'])
def hello_user():
return 'Hello User!'
# 傳遞參數(shù)
@app.route('/user/<id>')
def hello_id(id):
return 'Hello id:{}'.format(id)
@app.route('/query_user')
def query_id():
id = request.args.get('id')
# 訪問(wèn):http://127.0.0.1:5000/query_user?id=12345
return 'query_user id:{}'.format(id)
# 方向路由:通過(guò)視圖函數(shù),反找出url地址
@app.route('/query_url')
def query_url():
# 訪問(wèn):http://127.0.0.1:5000/query_url
return 'query_url:{}'.format(url_for('query_id'))
if __name__ == '__main__':
app.run()
1.3 flask 模版
1.3.1 html中條件語(yǔ)句
{% if user %}
user_name: {{ user.user_name }}
{% else %}
no this user
{% endif %}
1.3.2 html循環(huán)語(yǔ)句
{% for user in user_li %}
{{ user.user_id }}--{{ user.user_name }}<br>
{% endfor %}
1.3.3 html 繼承
> 父類
<div>
<h1>header</h1>
</div>
{% block content %}
{% endblock %}
<div>
<h1>footer</h1>
</div>
> 子類
{% extends "base.html" %}
{% block content %}
<h2>this is page one</h2>
{% endblock %}
> 調(diào)用
@app.route('/base_two')
def base_two():
return render_template('base_two.html')
@app.route('/base_one')
def base_one():
return render_template('base_one.html')
1.4 flask 消息提示與異常處理-flash
> from flask import flash, render_template, request, abort
# 使用flash時(shí),需要使用app.secret_key='123'加密
app.secret_key = "123"
@app.errorhandler(404)
def not_found(e):
return render_template('404.html')
<h2>{{ get_flashed_messages()[0] }}</h2>
1.5 python web 開(kāi)發(fā)
1.5.1 get和post方法:
>get 請(qǐng)求可被瀏覽器緩存
>get 請(qǐng)求會(huì)保存在歷史記錄中
>get 請(qǐng)求有長(zhǎng)度限制
>get 請(qǐng)求不應(yīng)用與敏感場(chǎng)合
>post 請(qǐng)求不會(huì)顯示在URL中,包含在http請(qǐng)求頭中,使用ssh加密
1.5.2 python中的web服務(wù)器
>python自帶包創(chuàng)建服務(wù)器:
> BaseHTTPServer->提供基本的web服務(wù)和處理類
> SimpleHTTPServer -> 包含執(zhí)行g(shù)et請(qǐng)求SimpleHTTPRequestHandler
> CGIHTTPServer->包含處理post請(qǐng)求和執(zhí)行CGIHTTPRequestHandler
>
>在根目錄下執(zhí)行:
>在python2.6里啟動(dòng)CGI服務(wù)命令是:
python -m CGIHTTPServer 8080
>在python3.4里則是:
python -m http.server --cgi 8083
[[在Python2.6版本里,/usr/bin/lib/python2.6/ 目錄下會(huì)有 BaseHTTPServer.py, SimpleHTTPServer.py, CGIHTTPServer.py,但是在Python3.4里,就沒(méi)有上面的3個(gè)文件,而是合閉到了 /usr/bin/python3.4/http/server.py文件里了。]]
> 創(chuàng)建文件夾cgi-bin, views
> 在cgi-bin 中創(chuàng)建main.js
> #!/usr/bin/python //必須加這一行才能在命令行中執(zhí)行腳本
print("Content-type:text/html \n\n")
print("hello web development")
> 訪問(wèn): http://localhost:8083/cgi-bin/main.py
> get請(qǐng)求
> #!/usr/bin/python
#coding:utf-8
import cgi, cgitb
form1 = cgi.FieldStorage() #創(chuàng)建一個(gè)實(shí)例
name = form1.getvalue("name")
print("Content-type:text/html \n\n")
print("hello {}".format(name))
> 訪問(wèn): http://localhost:8083/cgi-bin/main.py?name=hahaha
1.5.3 表單
1.5.3.1 表單種類
<form name="form1">
//文本框<input type="text" placeholder="text" name="text1" />
//密碼框<input type="password" placeholder="password"/>
//文本輸入框<textarea style="resize: none" placeholder="textarea"></textarea>
//文件上傳<input type="file"/>
//單選框<input type="radio" name="Option" value="Option1"/>Option 1
<input type="radio" name="Option" value="Option2"/>Option 2
//復(fù)選框<input type="checkbox" name="Option" value="Option1"/>Option 3
<input type="checkbox" name="Option" value="Option2"/>Option 4
<input type="submit">
<input type="reset">
<input type="button" value="button">
</form>
1.5.3.2 表單提交方式
>get:
>請(qǐng)求可以被緩存
>請(qǐng)求有長(zhǎng)度限制
>請(qǐng)求數(shù)據(jù)暴露在url中 ,存在安全問(wèn)題
>適用場(chǎng)合:
>單純請(qǐng)求數(shù)據(jù),如:查詢數(shù)據(jù),不用插入數(shù)據(jù)庫(kù)時(shí)
>表單數(shù)據(jù)較短,不超過(guò)1024個(gè)字符
>post:
>url可以被緩存,但數(shù)據(jù)不會(huì)被緩存
>請(qǐng)求不便于分享
>沒(méi)有長(zhǎng)度限制
>適用場(chǎng)合:
>不僅請(qǐng)求數(shù)據(jù),如:需將數(shù)據(jù)插入數(shù)據(jù)庫(kù)中
>表單數(shù)據(jù)過(guò)長(zhǎng),超過(guò)1024個(gè)字符
>要傳送的數(shù)據(jù)不是ascii編碼
1.5.3.3 表單擴(kuò)展Flask-wtf:
> 安裝:
> 使用:
from wtforms import Form, TextField, PasswordField, validators
1.5.4 數(shù)據(jù)庫(kù)-python連接數(shù)據(jù)庫(kù)mysql
1.5.4.1 python 操作mysql
1.5.4.1.1連接數(shù)據(jù)庫(kù)
import pymysql
#連接數(shù)據(jù)庫(kù)
# db = pymysql.connect(host,port,user,passwd,db)
db = pymysql.connect("localhost","root","666666","test")
#使用cursor()方法創(chuàng)建一個(gè)游標(biāo)對(duì)象
cursor = db.cursor()
#使用execute()方法執(zhí)行SQL語(yǔ)句
cursor.execute("SELECT * FROM userinfo")
#使用fetall()獲取全部數(shù)據(jù)
data = cursor.fetchall()
#打印獲取到的數(shù)據(jù)
print(data)
#關(guān)閉游標(biāo)和數(shù)據(jù)庫(kù)的連接
cursor.close()
db.close()
1.5.4.1.2 數(shù)據(jù)庫(kù)增刪改操作 // commit()方法:在數(shù)據(jù)庫(kù)里增、刪、改的時(shí)候,必須要進(jìn)行提交,否則插入的數(shù)據(jù)不生效。
1.5.4.1.2.1 增
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo (username,passwd) VALUES('jack','123')"
cursor.execute(sql)
db.commit() #提交數(shù)據(jù)
cursor.close()
db.close()
1.5.4.1.2.2 增
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
cursor.execute(sql,("bob","123"))
db.commit() #提交數(shù)據(jù)
cursor.close()
db.close()
1.5.4.1.2.3 增加多條
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "INSERT INTO userinfo(username,passwd) VALUES(%s,%s)"
cursor.executemany(sql,[("tom","123"),("alex",'321')])
db.commit() #提交數(shù)據(jù)
cursor.close()
db.close()
1.5.4.1.2.4 查 fetchone():獲取下一行數(shù)據(jù),第一次為首行;
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchone() #第一次執(zhí)行
print(res)
res = cursor.fetchone() #第二次執(zhí)行
print(res)
cursor.close()
db.close()
1.5.4.1.2.6 查 fetchall() 獲取所有行數(shù)據(jù)源
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
cursor = db.cursor()
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchall() #第一次執(zhí)行
print(res)
res = cursor.fetchall() #第二次執(zhí)行
print(res)
cursor.close()
db.close()
#運(yùn)行結(jié)果
((1, 'frank', '123'), (2, 'rose', '321'), (3, 'jeff', '666'), (5, 'bob', '123'), (8, 'jack', '123'), (10, 'zed', '123'))
()
1.5.4.1.2.7 查 fetchmany(4):獲取下4行數(shù)據(jù)
> cursor = db.cursor(cursor=pymysql.cursors.DictCursor) #在實(shí)例化的時(shí)候,將屬性cursor設(shè)置為pymysql.cursors.DictCursor
> cursor.scroll(1,mode='relative') # 相對(duì)當(dāng)前位置移動(dòng),正數(shù)為光標(biāo)向后移動(dòng),負(fù)數(shù)為光標(biāo)向前移動(dòng);1,當(dāng)前光標(biāo)向后移動(dòng)1個(gè)位置
cursor.scroll(-1, mode='relative') #表示當(dāng)前光標(biāo)向前移動(dòng)一個(gè)位置
cursor.scroll(2,mode='absolute') # 相對(duì)絕對(duì)位置移動(dòng),表示光標(biāo)移到第二位
第一個(gè)值為移動(dòng)的行數(shù),整數(shù)為向下移動(dòng),負(fù)數(shù)為向上移動(dòng),mode指定了是相對(duì)當(dāng)前位置移動(dòng),還是相對(duì)于首行移動(dòng)
1.5.4.1.2.8 改
1.5.4.1.2.9 刪
1.5.4.1.3 上下文協(xié)議:
import pymysql
config={
"host":"127.0.0.1",
"user":"root",
"password":"LBLB1212@@",
"database":"dbforpymysql"
}
db = pymysql.connect(**config)
with db.cursor(cursor=pymysql.cursors.DictCursor) as cursor: #獲取數(shù)據(jù)庫(kù)連接的對(duì)象
sql = "SELECT * FROM userinfo"
cursor.execute(sql)
res = cursor.fetchone()
print(res)
cursor.scroll(2,mode='relative')
res = cursor.fetchone()
print(res)
cursor.close()
db.close()
1.5.5 數(shù)據(jù)庫(kù)-orm:
1.5.1 flask擴(kuò)展- Flask-SQLALchemy
1.5.2
1.5.3
1.5.4
1.5.5
1.5.6
1.5.7
1.6 數(shù)據(jù)庫(kù)使用介紹
-1.6.1 flask 外部腳本
-1.6.1.1 Flask-Script安裝與使用
> pip install flask-script
-1.6.1.2 Flask使用sqlite
1.6.2 flask 使用mysql
1.6.3 flask 使用mongodb
1.6.3.1 MongoDB 驅(qū)動(dòng):
1.6.3.1.1 Pymongo
>manage.py
from flask_script import Manager
from app import app
from modules import User
manager = Manager(app)
@manager.command
def save():
user = User('jike', 'jike@jikexueyuan.com')
user.save()
@manager.command
def query_users():
users = User.query_users()
for user in users:
print(user)
if __name__ == "__main__":
manager.run()
>modules.py
import pymongo
MONGO_URL = '127.0.0.1'
MONGO_DB = "jikexueyuan" #數(shù)據(jù)庫(kù)名稱
MONGO_TABLE = "user_collection" #表單名稱
def get_collection():
client = pymongo.MongoClient(MONGO_URL)
db = client[MONGO_DB]
user_collection = db[MONGO_TABLE]
return user_collection
class User():
def __init__(self, name, email):
self.name = name
self.email = email
def save(self):
user_info = {
"name": self.name,
"email": self.email
}
collection = get_collection()
id = collection.insert(user_info)
print(id)
@staticmethod
def query_users():
users = get_collection().find()
return user
>app.py
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World'
if __name__ == "__main__":
app.run()
>運(yùn)行:
->python manage.py save
->python manage.py query_users
1.6.3.1 MongoDB中的orm:
1.6.3.1.1 MongoEngine:
>安裝: pip install flask-mongoengine

浙公網(wǎng)安備 33010602011771號(hào)