提交 5e3da5f4 编写于 作者: C Corley

V1.0

上级
### 安装环境依赖
在克隆或下载项目后,在项目目录下执行`pip install -r requirements.txt`命令安装项目所需库。
### 项目版本
#### V1.0
项目整体目录框架搭建完毕,后台管理员模型创建完成,实现命令行添加用户,后台登录页面实现。
\ No newline at end of file
from datetime import datetime
from werkzeug.security import generate_password_hash
from exts import db
class CMSUser(db.Model):
'''后台管理员用户类'''
__tablename__ = 'cms_user'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(30), nullable=False)
_password = db.Column(db.String(100), nullable=False)
email = db.Column(db.String(50), nullable=False, unique=True)
join_time = db.Column(db.DateTime, default=datetime.now())
def __init__(self, username, password, email):
self.username = username
self.password = password
self.email = email
@property
def password(self):
return self._password
@password.setter
def password(self, raw_password):
self._password = generate_password_hash(raw_password)
from flask import Blueprint, render_template, views
cms_bp = Blueprint('cms', __name__, url_prefix='/cms')
@cms_bp.route('/')
def index():
return '后台管理首页'
class LoginView(views.MethodView):
def get(self):
return render_template('cms/cms_login.html')
cms_bp.add_url_rule('/login/', view_func=LoginView.as_view('login'))
\ No newline at end of file
from flask import Blueprint
front_bp = Blueprint('front', __name__)
@front_bp.route('/')
def index():
return '前台首页'
\ No newline at end of file
'''
前台 front
后台 cms
公有 common
'''
from flask import Flask
from exts import db
from apps.cms.views import cms_bp
from apps.front.views import front_bp
import config
app = Flask(__name__)
app.config.from_object(config)
app.config['TEMPLATE_AUTO_RELOAD'] = True
db.init_app(app)
app.register_blueprint(cms_bp)
app.register_blueprint(front_bp)
if __name__ == '__main__':
app.run(debug=True)
\ No newline at end of file
# 数据库连接配置
HOSTNAME = '127.0.0.1'
PORT = 3306
USERNAME = 'root'
PASSWORD = 'root'
DATABASE = 'flask_bbs'
DB_URL = 'mysql+mysqlconnector://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME, PASSWORD, HOSTNAME, PORT, DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URL
SQLALCHEMY_TRACK_MODIFICATIONS = False
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
\ No newline at end of file
from flask_script import Manager
from bbs import app
from flask_migrate import Migrate, MigrateCommand
from exts import db
from apps.cms.models import CMSUser
manager = Manager(app)
Migrate(app, db)
manager.add_command('db', MigrateCommand)
@manager.option('-u', '--username', dest='username')
@manager.option('-p', '--password', dest='password')
@manager.option('-e', '--email', dest='email')
def create_cms_user(username, password, email):
user = CMSUser(username=username, password=password, email=email)
db.session.add(user)
db.session.commit()
print('CMS用户添加成功')
if __name__ == '__main__':
manager.run()
Generic single-database configuration.
\ No newline at end of file
# A generic, single database configuration.
[alembic]
# template used to generate migration files
# file_template = %%(rev)s_%%(slug)s
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
from __future__ import with_statement
import logging
from logging.config import fileConfig
from sqlalchemy import engine_from_config
from sqlalchemy import pool
from alembic import context
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
# Interpret the config file for Python logging.
# This line sets up loggers basically.
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app
config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
target_metadata = current_app.extensions['migrate'].db.metadata
# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
def run_migrations_offline():
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
url = config.get_main_option("sqlalchemy.url")
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True
)
with context.begin_transaction():
context.run_migrations()
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
# this callback is used to prevent an auto-migration from being generated
# when there are no changes to the schema
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
def process_revision_directives(context, revision, directives):
if getattr(config.cmd_opts, 'autogenerate', False):
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
logger.info('No changes in schema detected.')
connectable = engine_from_config(
config.get_section(config.config_ini_section),
prefix='sqlalchemy.',
poolclass=pool.NullPool,
)
with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
process_revision_directives=process_revision_directives,
**current_app.extensions['migrate'].configure_args
)
with context.begin_transaction():
context.run_migrations()
if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
"""${message}
Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}
"""
from alembic import op
import sqlalchemy as sa
${imports if imports else ""}
# revision identifiers, used by Alembic.
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
def upgrade():
${upgrades if upgrades else "pass"}
def downgrade():
${downgrades if downgrades else "pass"}
"""empty message
Revision ID: 99eda37c54a8
Revises:
Create Date: 2020-05-18 20:22:12.634486
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '99eda37c54a8'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('cms_user',
sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('username', sa.String(length=30), nullable=False),
sa.Column('password', sa.String(length=30), nullable=False),
sa.Column('email', sa.String(length=50), nullable=False),
sa.Column('join_time', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email')
)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('cms_user')
# ### end Alembic commands ###
"""empty message
Revision ID: f7a47bdbaa71
Revises: 99eda37c54a8
Create Date: 2020-05-18 20:41:53.508066
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = 'f7a47bdbaa71'
down_revision = '99eda37c54a8'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('cms_user', sa.Column('_password', sa.String(length=100), nullable=False))
op.drop_column('cms_user', 'password')
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('cms_user', sa.Column('password', mysql.VARCHAR(length=30), nullable=False))
op.drop_column('cms_user', '_password')
# ### end Alembic commands ###
alembic==1.4.2
aniso8601==8.0.0
click==7.1.1
dnspython==1.16.0
Flask==1.1.2
Flask-Migrate==2.5.3
Flask-RESTful==0.3.8
Flask-Script==2.0.6
Flask-SQLAlchemy==2.4.1
Flask-WTF==0.14.3
itsdangerous==1.1.0
Jinja2==2.11.2
Mako==1.1.2
MarkupSafe==1.1.1
mysql-connector==2.2.9
mysql-connector-python==8.0.19
protobuf==3.6.1
PyMySQL==0.9.3
python-dateutil==2.8.1
python-editor==1.0.4
pytz==2020.1
six==1.14.0
SQLAlchemy==1.3.16
Werkzeug==1.0.1
WTForms==2.3.1
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
\ No newline at end of file
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="{{ url_for('static', filename='cms/images/bbs-favicon.ico') }}">
<title>CMS用户登录</title>
<!-- Bootstrap core CSS -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="{{ url_for('static', filename='cms/css/signin.css') }}" rel="stylesheet">
<![endif]-->
</head>
<body>
<div class="container">
<form class="form-signin" method="post">
<h2 class="form-signin-heading">请登录</h2>
<label for="inputEmail" class="sr-only">邮箱地址</label>
<input type="email" id="inputEmail" class="form-control" name="email" placeholder="邮箱地址" required autofocus>
<label for="inputPassword" class="sr-only">密码</label>
<input type="password" id="inputPassword" class="form-control" name="password" placeholder="密码" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me" name="remember"> 记住我
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">立即登录</button>
</form>
</div> <!-- /container -->
</body>
</html>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册