验证码:
步骤:
1. 生成验证码
pip install pillow
from PIL import Image, ImageFont, ImageDraw, ImageFilter
2. image对象 code验证码
3.
/login
GET:
渲染
login.html
|--- <img src="{{url_for('blog.pic')}}" alt="ABC" style="height:34px;" id="pic">
POST:
获取数据
验证码的匹配
验证用户和密码(check_password_hash)
session['uname'] =
重定向到首页
/pic
image对象 code验证码
将image对象转成二进制
make_response(buf_bytes) ---->response
response.headers['Content-Type']= 'image/jpg'
session['code']=code验证码
return response
缓存中:
pip install redis
pip install flask-caching
启动redis
进到redis目录:
redis-server redis.windows.conf
使用缓存:
1. Cache对象
from flask-caching import Cache
cache = Cache()
2.
config = {
'CACHE_TYPE': 'redis',
'CACHE_REDIS_HOST': '127.0.0.1',
'CACHE_REDIS_PORT': 6379
}
def create_app():
.....
cache.init_app(app,config)
3. 设置缓存:
cache.set(key,value,timeout=second) ----> flask_cache_pic_abc
cache.set_many([(key,value),(key,value),(key,value),...])
获取缓存值:
cache.get(key) --->value
cache.get_many(key1,key2,...)
删除缓存:
cache.delete(key)
cache.delete_many(key1,key2,...)
cache.clear()
视图函数缓存:
@app.route("/")
@cache.cached(timeout=50)
def index():
return render_template('index.html')
SMS: 手机验证码
- 获取验证码:
-
输入手机号码
-
通过ajax发送请求
-
后端: 获取手机号码
使用requests向第三方的服务端(网易云信)发送请求
URL https://api.netease.im/sms/sendcode.action
method: POST
header:
headers={}
headers[‘Content-Type’] = ‘application/x-www-form-urlencoded;charset=utf-8’
AppSecret = ‘ee8d51d1061e’
Nonce = ‘74093849032804’
CurTime = str(time.time())
headers[‘AppKey’] = ‘cc735ffe22684cc4dab2dc943540777c’
headers[‘Nonce’] = Nonce
headers[‘CurTime’] = CurTime
s = AppSecret + Nonce + CurTime
headers[‘CheckSum’] = hashlib.sha1(s.encode(‘utf-8’)).hexdigest().lower()
res = requests.post(url, data={‘mobile’: phone}, headers=headers)
4.获取响应对象:
res.text 文本内容
res.content 二进制 -
转成json对象
r = json.loads(res.text)r.obj —> 验证码
保存到缓存中: cache.set(phone,r.obj)
-
返回json结果给ajax
-
2.登录验证:
获取手机号码和验证码进行验证
phone = request.form.get(‘phone’)
validate = request.form.get(‘valiadate’)
code = cache.get(phone)
if code == validate:
user = User.query.filter(User.phone == phone).first()
cache.set(‘uname’, user.username)
session[‘uname’] = user.username
return redirect(url_for(‘blog.index’))
else:
flash(‘手机验证码错误’)
return render_template(‘login_phonecode.html’)
七牛云存储:
nginx:
安装可以参照的路径:
http://nginx.org/en/linux_packages.html#Ubuntu
启动Nginx
nginx [ -c configpath] 默认配置目录:/etc/nginx/nginx.conf
信息查看
nginx -v
nginx -V
查看进程:
ps -ef |grep nginx
控制Nginx
nginx -s signal
stop 快速关闭
quit 优雅的关闭
reload 重新加载配置
通过系统管理
systemctl status nginx 查看nginx状态
systemctl start nginx 启动nginx服务
systemctl stop nginx 关闭nginx服务
systemctl enable nginx 设置开机自启
systemctl disable nginx 禁止开机自启