flask 簡介
- Flask是一個基於python的,微型web框架。之所以被稱爲微型是因爲其核心非常簡單,同時具有很強的擴展能力。它幾乎不給使用者做任何技術決定。 安裝flask時應該注意其必須的幾個支持包比如Jinja2,Werkzeug等,flask還有一些可選的輔助模塊,使用它們可以讓程序更加簡潔易懂,比如SQLAlchemy用於數據庫的連接和操作,flask-WTForm用於網頁上表單的設計
flask 常用 模塊安裝以及文檔
- flask中文文檔https://dormousehole.readthedocs.io/en/latest/ 安裝pip install flask
- Jinja2(模板語法)中文文檔http://docs.jinkan.org/docs/jinja2/ flask自帶的,無需安裝
- SQLAlchemy(操作數據庫)中文文檔http://www.pythondoc.com/flask-sqlalchemy/quickstart.html# 安裝 pip install flask-sqlalchemy
- Flask-WTF(表單操作)中文文檔http://www.pythondoc.com/flask-wtf/ 安裝pip install Flask-WTF
- 自動生成依賴包信息
pip freeze>Requirements.txt
- 安裝依賴包
pip install -r Requirements.txt
- 一個簡單的flask應用
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "<h1>Hello,World</h1>"
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000,debug=True,threaded=True)
flask 連接mysql數據庫
- 由於使用Python3開發語言,python3中已經不再支持MySQLdb模塊,所以這裏使用pymysql數據庫連接組件,安裝pymysql
pip install pymysql
- Flask擁有豐富的擴展組件,數據庫管理方面Flask-SQLAlchemy簡化了數據庫管理的操作。SQLAlchemy是一個很強大的關係型數據庫框架,支持多種數據庫後臺。其不但提供了高層ORM,而且也提供了使用數據庫原生SQL的底層功能。和其他大多數擴展一樣,Flask-SQLAlchemy也使用pip安裝:
pip install flask-sqlalchemy
mysql連接配置
# coding:utf8
import pymysql
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@localhost:3306/artcms" #連接數據庫
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True
db = SQLAlchemy(app)
"""
用戶模型
1:編號
2:賬號
3:密碼
4:註冊時間
"""
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True) # 編號主鍵
name = db.Column(db.String(20), nullable=False) # 賬號不爲空
pwd = db.Column(db.String(100), nullable=False) # 密碼不爲空
addtime = db.Column(db.DateTime, nullable=False) # 註冊時間不爲空
def __repr__(self):
return "<User %r>" % self.name
"""
文章模型
1:編號
2:標題
3:分類
4:作者
5:封面
6:內容
7:發佈時間
"""
class Art(db.Model):
__tablename__ = 'art'
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False) # 標題
cate = db.Column(db.Integer, nullable=False) # 分類
user_id = db.Column(db.Integer, nullable=False) # 作者
logo = db.Column(db.Integer, nullable=False) # 封面
content = db.Column(db.Text, nullable=False) # 內容
addtime = db.Column(db.DateTime, nullable=False) # 發佈時間
def __repr__(self):
return "<Art %r>" % self.title
if __name__ == '__main__':
db.create_all() #創建表
數據庫配置出現的問題
- 在創建表時出現‘ImportError: No module named MySQLdb’錯誤提示
- 配置之前
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:root@localhost:3306/artcms" #連接數據庫
- 改爲mysql+pymysql
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql+pymysql://root:root@localhost:3306/artcms" #連接數據庫
進入mysql client端,查看數據表
- 輸入密碼:
![]
- 輸入\s 查看,用戶名,端口號
- 輸入show databases; 查看數據庫名稱
- 輸入use 數據庫名稱
- 輸入show tabels; 查看art表和user表
-
- desc 表名;查看錶的字段
關於flask-sqlalchemy版本2.3問題點
- flask中KeyError: 'SQLALCHEMY_TRACK_MODIFICATIONS'
- 解決方法: 把flask-sqlalchemy換成2.1版本
- pip uninstall flask-sqlalchemy
- pip install flask-sqlalchemy == 2.1
關於驗證碼pillow
- 使用:pip install pillow
- 創建code.py
# coding utf:8
import os
import random
# 確認唯一性
import uuid
from PIL import Image, ImageDraw, ImageFont, ImageFilter
# 定義驗證碼功能
class Code:
# 隨機一個字母或者數字
def random_chr(self):
num = random.randint(1, 3)
if num == 1:
# 隨機一個0-9之間的數字
char = random.randint(48, 57)
elif num == 2:
# 隨機一個a-z之間的數字
char = random.randint(87, 122)
else:
# 隨機一個A-Z之間的數字
char = random.randint(65, 90)
return chr(char)
# 定義干擾之符
def random_dis(self):
arr = ["^", "_", "-", ".", "~"]
return arr[random.randint(0, len(arr) - 1)]
# 定義干擾字符顏色, 三原色,RGB, 0-255
def random_color1(self):
return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))
# 定義字符顏色
def random_color2(self):
return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))
# 創建驗證碼
def create_code(self):
width = 240
height = 60
image = Image.new("RGB", (width, height), (192, 192, 192))
# 創建font對象,定義字體和大小
font_name = random.randint(1, 3)
font_file = os.path.join(os.path.dirname(__file__), "static/fonts") + "/%d.ttf" % font_name
# 創建字體
# font = ImageFont.load_default().font
font = ImageFont.truetype(font_file, 30)
# 創建畫布
draw = ImageDraw.Draw(image)
# 填充像素點
for x in range(0, width, 5):
for y in range(0, height, 5):
draw.point((x, y), fill=self.random_color1())
# 填充干擾字符
for v in range(0, width, 30):
dis = self.random_dis()
w = 5 + v
# 距離圖片上邊距最多15個像素,最低5個像素
h = random.randint(5, 15)
draw.text((w, h), dis, font=font, fill=self.random_color1())
# 填充字符
chars = ''
for v in range(4):
c = self.random_chr()
chars += str(c)
# 距離圖片上邊距最多15個像素,最低5個像素
h = random.randint(5, 15)
# 佔圖片的1/4,距離10px
w = width/4 * v + 10
draw.text((w, h), c, font=font, fill=self.random_color2())
# 模糊效果
image.filter(ImageFilter.BLUR)
image_name = "%s.jpg" % uuid.uuid4().hex
# 獲取本地路徑
save_dir = os.path.join(os.path.dirname(__file__), "static/code")
# 判斷路徑存不存在
if not os.path.exists(save_dir):
os.makedirs(save_dir)
image.save(save_dir + "/" + image_name, "jpeg")
return dict(
img_name=image_name,
code=chars
)
image.show()
if __name__ == "__main__":
c = Code()
# print(c.random_chr())
print(c.random_color1())
print(c.random_color2())
c.create_code()
遇到問題點
- python 讀取文件時報錯UnicodeDecodeError: 'gbk' codec can't decode byte 0x80 in position 205: illegal multibyte sequence
- 修改之前:
with open(image) as f:
image = f.read()
- 修改以後
with open(image, 'rb') as f:
image = f.read()
問題點
- AttributeError: 'SecureCookieSession' object has no attribute 'has_key'
- 修改前
自定義驗證碼功能
def validate_code(self, field):
code = field.data
if not session.has_key('code'):
raise ValidationError('沒有驗證碼')
if session.has_key('code') and session["code"] != code:
raise ValidationError('驗證碼不正確!')
- python版本的原因,用session對象的__contains__()方法替換has_key()方法。
- 修改後
# 自定義驗證碼功能
def validate_code(self, field):
code = field.data
if not session.__contains__('code'):
raise ValidationError('沒有驗證碼')
if session.__contains__('code') and session["code"] != code:
raise ValidationError('驗證碼不正確!')