flask項(xiàng)目:新聞信息網(wǎng)站2藍(lán)圖的創(chuàng)建

開發(fā)模式

config.py:

import logging

import redis


class Config(object):
    """工程信息配置"""
    SECRET_KEY = "EjpNVSNQTyGi1VvWECj9TvC/+kq3oujee2kTfQUs8yCM6xX9Yjq52v54g+HVoknA"

    DEBUG = True
    # 導(dǎo)入數(shù)據(jù)庫配置
    # 設(shè)置數(shù)據(jù)庫連接
    SQLALCHEMY_DATABASE_URI= 'mysql://root:root@127.0.0.1:3306/information'
    # 動(dòng)態(tài)追蹤設(shè)置
    SQLALCHEMY_TRACK_MODUFICATIONS = True
    # 顯示原始sql
    SQLALCHEMY_ECHO = True

    REDIS_HOST = "127.0.0.1"
    REDIS_POST = 6379
    # flask_session配置信息
    SESSION_TYPE = 'redis' #指定session保存到Redis中
    SESSION_USE_SIGNER = True   #讓cookie中的sessionid 被加密處理
    # 使用Redis實(shí)例
    SESSION_REDIS = redis.StrictRedis(host=REDIS_HOST, port=REDIS_POST)
    SESSION_PERMANENT = False
    PERMANENT_SESSION_LIFETIME = 86400  #session有效期  秒

    #日志級(jí)別
    LEVEL = logging.DEBUG
# 開發(fā)環(huán)境
class DevelopConfig(Config):
    pass
# 生產(chǎn)環(huán)境
class ProductConfig(Config):
    DEBUG = False
    LEVEL = logging.ERROR

# 測(cè)試環(huán)境
class TestingConfig(Config):
    TESTING = True
# 通過統(tǒng)一的字典進(jìn)行配置類的訪問
config_dict = {
    "develop":DevelopConfig,
    "product":ProductConfig,
    "testing":TestingConfig,
}

添加了3個(gè)類



__ init__.py:創(chuàng)建了一個(gè)create_app類包裝

from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_wtf import CSRFProtect
from config import *

db = SQLAlchemy()

def create_app(config_name):
    """通過傳入不同的得配置名,切換不同的環(huán)境"""
    config = config_dict.get(config_name)


    app = Flask(__name__)
    app.config.from_object(Config)

    # 初始化Redis配置
    # redis.StrictRedis(host=Config.REDIS_HOST, port=Config.REDIS_POST)
    # 開啟csrf保護(hù),只用于服務(wù)器驗(yàn)證功能
    CSRFProtect(app)
    # 設(shè)置session保存指定位置
    Session(app)
    return app

manage.py:初始化create_app

# @File    : manage.py 只負(fù)責(zé)基本的啟動(dòng)工作,
# app 的創(chuàng)建在 info 下的__init__ 中
from flask import session
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from info import create_app, db


app = create_app('develop')
# flask_script
manager = Manager(app)
# 數(shù)據(jù)庫遷移
Migrate(app, db)
manager.add_command('db', MigrateCommand)

@app.route('/')
def index():
    session['name'] = 'ssq'
    return 'index'

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

記錄日志

__ init__.py:添加了log_file類,
在creat_app中設(shè)置日志等級(jí),
在config.py設(shè)置日志級(jí)別。

# 記錄日志
def log_file(level):
    # 設(shè)置日志的記錄等級(jí),常見等級(jí)有: DEBUG<INFO<WARING<ERROR
    logging.basicConfig(level=level)  # 調(diào)試debug級(jí)
    # 創(chuàng)建日志記錄器,指明日志保存的路徑、每個(gè)日志文件的最大大小、保存的日志文件個(gè)數(shù)上限
    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)
    # 創(chuàng)建日志記錄的格式 日志等級(jí) 輸入日志信息的文件名 行數(shù) 日志信息
    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')
    # 為剛創(chuàng)建的日志記錄器設(shè)置日志記錄格式
    file_log_handler.setFormatter(formatter)
    # 為全局的日志工具對(duì)象(flask app使用的)添加日志記錄器
    logging.getLogger().addHandler(file_log_handler)


最后創(chuàng)建logs文件,運(yùn)行后進(jìn)入頁面會(huì)有日志生成在文件中


藍(lán)圖的創(chuàng)建

  • 創(chuàng)建藍(lán)圖
  • 注冊(cè)藍(lán)圖路由
  • 注冊(cè)藍(lán)圖到程序?qū)嵗?br> 在info下創(chuàng)建moudles包,下在創(chuàng)建index包



    在index下的__ init__.py下添加如下代碼:創(chuàng)建藍(lán)圖

# 創(chuàng)建藍(lán)圖
from flask import Blueprint

index_blu = Blueprint('index',__name__)
from  . import views

將manage.py中的首頁路由函數(shù)部分剪切到index下創(chuàng)建的views.朋友下,并導(dǎo)入index_blu,并將app修改

from . import index_blu

@index_blu.route('/')
def index():
    return 'index'

最后在info下的__ init__.py中注冊(cè)藍(lán)圖

注冊(cè)藍(lán)圖時(shí),導(dǎo)入注冊(cè)寫在一起

# 注冊(cè)藍(lán)圖時(shí),導(dǎo)入注冊(cè)寫在一起
    from  info.moudles.index import  index_blu
    app.register_blueprint(index_blu)

首頁

創(chuàng)建static文件并導(dǎo)入資源, 創(chuàng)建templates文件,文件下創(chuàng)建news文件,將static下news中的index.html拖入templates下news中,最后修改views.py

from flask import render_template
from . import index_blu

@index_blu.route('/')
def index():
    # return 'index'
    return render_template('news/index.html')

數(shù)據(jù)庫遷移

  1. 在Terminal寫入
python manage.py db init

會(huì)出現(xiàn)


image.png

2.創(chuàng)建SQLAlchemy對(duì)象關(guān)聯(lián)app,再在terminal中輸入


python manage.py db migrate -m"initial"

3.在terminal中輸入

python manage.py db upgrade

最后添加數(shù)據(jù)

ico

views.py添加

@index_blu.route('/favicon.ico')
def get_web_logo():
    return current_app.send_static_file('news/favicon.ico')
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容