flask项目的其他配置

2.1redis数据库

2.1.1安装 
sudo apt-get install redis-server
2.1.2开启与关闭
开启redis服务器 redis-server
停止redis服务器 service redis stop
开启redis客户端 redis-cli
停止/退出客户端 quit/exit
查看redis服务器进程 ps aux | grep redis
切换数据库 select 10
2.2.3redis与python
	引入模块 from redis import *
	通过init创建对象
	host默认为localhost,port默认为6379,db默认为0
	sr = StrictRedis(host='localhost', port=6379, db=0)

2.2redis设置和session设置

# redis配置,把具体值设置赋给变量,方便后期修改
redis_store = StrictRedis(host='localhost', port=6379, db=0, , decode_responses = True)

# Session的配置
SESSION_TYPE = "redis"  # 指定 session 保存到 redis 中
SESSION_USE_SIGNER = True  # 让 cookie 中的 session_id 被加密签名处理
SESSION_REDIS = redis.StrictRedis(host=REDIS_HOST, port=REDIS_PORT)  # 使用 redis 的实例
SESSION_PERMANENT = False  # 设置与要过期
PERMANENT_SESSION_LIFETIME = 86400 * 2  # session 的有效期,单位是秒

Session(app)

2.3设置在相应中设置csrf_token

# 请求钩子函数,
@app.after_request
def after_request(response):
    """每次请求之后执行"""
    csrf_token = generate_csrf()
    response.set_cookie("csrf_token", csrf_token)
    return response

2.4统一处理404

@app.errorhandler(404)
@user_login_data
def page_not_found(e):
    user = g.user
    data = {"user": user.to_dict() if user else None}
    return render_template("news/404.html", data=data)

2.5设置日志

def setup_log(config_name):
	"""设置日志"""
	# 设置日志的记录等级
	logging.basicConfig(level=config[config_name].LOG_LEVEL)  # 调试debug级
	# 创建日志记录器,指明日志保存的路径、每个日志文件的最大大小(maxBytes)、保存的日志文件个数(backupCount)上限
	file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
	# 创建日志记录的格式 日志等级  输入日志信息的文件名 行数 日志信息
	formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
	# 为刚创建的日志记录器设置日志记录格式
	file_log_handler.setFormatter(formatter)
	# 为全局的日志工具对象(flask app使用的)添加日志记录器
	logging.getLogger().addHandler(file_log_handler)

2.6设置装饰器

def user_login_data(f):
	@functools.wraps(f)
	def wrapper(*args, **kwargs):
		user_id = session.get("user_id", None)
		user = None
		if user_id:
			# 尝试查询用户模型
			try:
				user = User.query.get(user_id)
			except Exception as e:
				current_app.logger.error(e)
		# 把查询出来的数据赋值给变量g
		g.user = user
		return f(*args, **kwargs)
	return wrapper
	
注册装饰器 app.add_template_filter(do_index_class, "index_class")

2.7七牛云传图片

from qiniu import Auth, put_data

access_key = "yV4GmNBLOgQK-1Sn3o4jktGLFdFSrlywR2C-hvsW"
secret_key = "bixMURPL6tHjrb8QKVg2tm7n9k8C7vaOeQ4MEoeW"
bucket_name = "ihome"

def storage(data):
	try:
		q = Auth(access_key, secret_key)
		token = q.upload_token(bucket_name)
		ret, info = put_data(token, None, data)
		print(ret, info)
	except Exception as e:
		raise e

	if info.status_code != 200:
		raise Exception("上传图片失败")
	return ret["key"]

if __name__ == '__main__':
	file = input('请输入文件路径')
	with open(file, 'rb') as f:
		storage(f.read())

猜你喜欢

转载自blog.csdn.net/weixin_42932562/article/details/82963561