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

32 篇文章 3 订阅

一.在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

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值