Python Flask框架学习30:redis操作/配置静态文件路径

一.在utils包下创建init.py

文档树如下:

è¿éåå¾çæè¿°

如下:

import os

from flask import Flask
from flask_session import Session
import redis

from App.views import blue

def create_app():

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    template_dir = os.path.join(BASE_DIR, 'templates')

    static_dir = os.path.join(BASE_DIR, 'static')
    # 初始化app
    app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)
    # 注册蓝图
    app.register_blueprint(blueprint=blue, url_prefix='/app/')

    # 设置密钥, 使用redis存储信息
    app.config['SECRET_KEY'] = 'secret_key'
    app.config['SESSION_TYPE'] = 'redis'

    #访问远程redis
    app.config['SESSION_REDIS'] = redis.Redis(host='114.116.4.186', port='6379',password='2905058')

    #定义前缀
    app.config['SESSION_KEY_PREFIX'] = 'flask'

    #第一种初始化app
    Session(app)

    #第二种方式
    # se = Session()
    # se.init_app(app)

    return app

 

在manage.py项目文件下为:
from flask_script import Manager

from App import create_app

app = create_app()

# 将app交给manage进行管理
manage = Manager(app=app)

if __name__ == '__main__':
    manage.run()

 

在views.py中进行操作,存取数据,删除数据
import random

from flask import Blueprint, render_template, request, session, redirect, url_for, make_response

# 蓝图用于管理url
blue = Blueprint('app', __name__)

@blue.route('/login/', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        username = session.get('username')
        return render_template('login.html', username=username)
    elif request.method == 'POST':
        username =request.form.get('username')
        session['username'] = username

        return redirect(url_for('app.login'))

@blue.route('/getresponse/')
def get_resopnse():

    response = make_response('<h2>我是大帅比</h2>')
    ticket = ''
    s = 'qwertyuiopasdfghjklzxcvbnm1234567890'
    for i in range(20):
        ticket += random.choice(s)
    response.set_cookie('ticket', ticket)
    return response

@blue.route('/deletecookie/')
def del_cookie():

    response = make_response('<h2>我是大帅比1</h2>')

    response.delete_cookie('ticket')
    return response

更多内容,可关注作者的微信公众号:胖哥真不错。

 

展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客
应支付0元
点击重新获取
扫码支付

支付成功即可阅读