Added blog app with model
This commit is contained in:
parent
4f5505ceba
commit
d73e57bff6
|
@ -1,9 +1,11 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from datetime import datetime
|
||||
import importlib
|
||||
|
||||
from flask import Flask, make_response, render_template, url_for
|
||||
from flask_admin import Admin
|
||||
from flask_admin.contrib.sqla import ModelView
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
|
||||
from . import conf
|
||||
|
||||
|
@ -18,6 +20,18 @@ app.static_folder = get_theme_folder(conf.STATIC_FOLDER)
|
|||
app.template_folder = get_theme_folder(conf.TEMPLATE_FOLDER)
|
||||
app.config['cdn_domain'] = conf.CDN_DOMAIN
|
||||
|
||||
# Database
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = conf.DATABASE_PATH
|
||||
db = SQLAlchemy(app)
|
||||
|
||||
# Enable admin if set in the conf
|
||||
if conf.ENABLE_ADMIN:
|
||||
admin = Admin(app, name='fmartingrcom', template_mode='bootstrap3')
|
||||
|
||||
# Method to register admin models
|
||||
def register_admin_model(model):
|
||||
admin.add_view(ModelView(model, db.session))
|
||||
|
||||
# Autoload enabled blueprints
|
||||
for blueprint in conf.BLUEPRINTS:
|
||||
module = importlib.import_module(
|
||||
|
|
|
@ -1,39 +1,27 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from flask import Blueprint, render_template, request, abort
|
||||
from peewee import CharField, DateTimeField
|
||||
|
||||
from fmartingrcom.db import Model
|
||||
#from flask_admin.contrib.sqla import ModelView
|
||||
from sqlalchemy import Column, String, Text, Integer, Boolean, DateTime
|
||||
from fmartingrcom import db, register_admin_model, conf
|
||||
|
||||
|
||||
blog = Blueprint('blog', __name__)
|
||||
|
||||
|
||||
# Models
|
||||
class Post(Model):
|
||||
HTML = 'html'
|
||||
MARKDOWN = 'md'
|
||||
TYPE_CHOICES = (
|
||||
(HTML, 'HTML'),
|
||||
(MARKDOWN, 'Markdown'),
|
||||
)
|
||||
class Post(db.Model):
|
||||
__tablename__ = 'blog_post'
|
||||
id = Column(Integer, primary_key=True)
|
||||
title = Column(String(250))
|
||||
slug = Column(String(250), index=True)
|
||||
date = Column(DateTime(True), index=True)
|
||||
content = Column(Text)
|
||||
html = Column(Text)
|
||||
draft = Column(Boolean, default=True)
|
||||
|
||||
title = CharField()
|
||||
slug = CharField()
|
||||
date = DateTimeField()
|
||||
type = CharField(choices=TYPE_CHOICES, default=HTML)
|
||||
|
||||
@property
|
||||
def content(self):
|
||||
filename = '{}-{}-{}-{}.{}'.format(self.date.year, self.date.month, self.date.day, self.slug, self.type)
|
||||
content = open('./content/blog/{}'.format(filename), 'r').read()
|
||||
|
||||
if self.type == self.MARKDOWN:
|
||||
import markdown2
|
||||
markdown = markdown2.Markdown()
|
||||
return markdown.convert(content)
|
||||
else:
|
||||
return content
|
||||
if conf.ENABLE_ADMIN:
|
||||
register_admin_model(Post)
|
||||
|
||||
|
||||
# Views
|
||||
|
@ -50,7 +38,15 @@ def blog_post(year, month, day, slug):
|
|||
|
||||
@blog.route('/blog/')
|
||||
def blog_list():
|
||||
try:
|
||||
page_num = int(request.args.get('page', 1))
|
||||
except ValueError:
|
||||
page_num = 1
|
||||
|
||||
query = Post.query.order_by(Post.date)
|
||||
paginator = query.paginate(page_num, 1)
|
||||
context = {
|
||||
'page': request.args.get('page', 1)
|
||||
'items': paginator.items,
|
||||
'paginator': paginator
|
||||
}
|
||||
return render_template('blog/list.html', **context)
|
||||
|
|
|
@ -1,5 +1,9 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
import os
|
||||
|
||||
PROJECT_PATH = os.getcwd()
|
||||
|
||||
# Enables or disables debug mode
|
||||
DEBUG = False
|
||||
|
||||
|
@ -9,6 +13,9 @@ SECRET_KEY = '0123456789'
|
|||
# Database URI
|
||||
DATABASE_PATH = '/tmp/fmartingr.db'
|
||||
|
||||
# Admin
|
||||
ENABLE_ADMIN = False
|
||||
|
||||
# Static and media files
|
||||
THEME = 'v2'
|
||||
CDN_DOMAIN = None
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
Model = declarative_base()
|
|
@ -1,13 +0,0 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from peewee import SqliteDatabase, Model as PeeweeModel
|
||||
|
||||
from . import conf
|
||||
|
||||
|
||||
db = SqliteDatabase(conf.DATABASE_PATH)
|
||||
db.connect()
|
||||
|
||||
class Model(PeeweeModel):
|
||||
class Meta:
|
||||
database = db
|
|
@ -1,5 +1,17 @@
|
|||
{% extends "blog/_base.html" %}
|
||||
|
||||
{% block main_content %}
|
||||
Blog, page {{ page }}
|
||||
{% for item in items %}
|
||||
{{ item.title }}
|
||||
{% endfor %}
|
||||
<hr >
|
||||
Blog, page {{ paginator.page }} of {{ paginator.pages }}
|
||||
{% if paginator.has_next %}
|
||||
<a href="{{ url_for('blog.blog_list') }}?page={{ paginator.next_num }}">Page {{ paginator.next_num }}</a>
|
||||
{% endif %}
|
||||
|
||||
{% if paginator.has_prev %}
|
||||
<a href="{{ url_for('blog.blog_list') }}?page={{ paginator.prev_num }}">Page {{ paginator.prev_num }}</a>
|
||||
{% endif %}
|
||||
|
||||
{% endblock %}
|
||||
|
|
|
@ -10,11 +10,11 @@ var minifyCss = require('gulp-minify-css');
|
|||
var livereload = require('gulp-livereload');
|
||||
var yargs = require('yargs').argv;
|
||||
|
||||
var default_theme = 'v2'
|
||||
var default_theme = 'v3'
|
||||
var theme = yargs.theme || default_theme;
|
||||
|
||||
gulp.task('sass', function () {
|
||||
var sassStream = gulp.src('./fmartingrcom/themes/' + theme + '/static/sass/style.sass')
|
||||
var sassStream = gulp.src('./fmartingrcom/themes/' + theme + '/static/sass/style.scss')
|
||||
.pipe(sass().on('error', sass.logError))
|
||||
var bowerStream = gulp.src([
|
||||
])
|
||||
|
@ -32,6 +32,6 @@ gulp.task('livereload', function () {
|
|||
|
||||
gulp.task('sass:watch', function () {
|
||||
livereload.listen();
|
||||
gulp.watch('./fmartingrcom/themes/' + theme + '/themes/sass/**/*.sass', ['sass']);
|
||||
gulp.watch('./fmartingrcom/themes/' + theme + '/themes/templates/**/*.html', ['livereload']);
|
||||
gulp.watch('./fmartingrcom/themes/' + theme + '/static/sass/**/*.scss', ['sass']);
|
||||
gulp.watch('./fmartingrcom/themes/' + theme + '/static/templates/**/*.html', ['livereload']);
|
||||
});
|
|
@ -0,0 +1,11 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
from flask_script import Manager
|
||||
from flask_migrate import Migrate, MigrateCommand
|
||||
import fmartingrcom
|
||||
|
||||
migrate = Migrate(fmartingrcom.app, fmartingrcom.db)
|
||||
manager = Manager(fmartingrcom.app)
|
||||
manager.add_command('db', MigrateCommand)
|
||||
|
||||
if __name__ == '__main__':
|
||||
manager.run()
|
|
@ -0,0 +1 @@
|
|||
Generic single-database configuration.
|
|
@ -0,0 +1,45 @@
|
|||
# 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
|
|
@ -0,0 +1,87 @@
|
|||
from __future__ import with_statement
|
||||
from alembic import context
|
||||
from sqlalchemy import engine_from_config, pool
|
||||
from logging.config import fileConfig
|
||||
import logging
|
||||
|
||||
# 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',
|
||||
current_app.config.get('SQLALCHEMY_DATABASE_URI'))
|
||||
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)
|
||||
|
||||
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.readthedocs.org/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.')
|
||||
|
||||
engine = engine_from_config(config.get_section(config.config_ini_section),
|
||||
prefix='sqlalchemy.',
|
||||
poolclass=pool.NullPool)
|
||||
|
||||
connection = engine.connect()
|
||||
context.configure(connection=connection,
|
||||
target_metadata=target_metadata,
|
||||
process_revision_directives=process_revision_directives,
|
||||
**current_app.extensions['migrate'].configure_args)
|
||||
|
||||
try:
|
||||
with context.begin_transaction():
|
||||
context.run_migrations()
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
if context.is_offline_mode():
|
||||
run_migrations_offline()
|
||||
else:
|
||||
run_migrations_online()
|
|
@ -0,0 +1,22 @@
|
|||
"""${message}
|
||||
|
||||
Revision ID: ${up_revision}
|
||||
Revises: ${down_revision}
|
||||
Create Date: ${create_date}
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = ${repr(up_revision)}
|
||||
down_revision = ${repr(down_revision)}
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
${imports if imports else ""}
|
||||
|
||||
def upgrade():
|
||||
${upgrades if upgrades else "pass"}
|
||||
|
||||
|
||||
def downgrade():
|
||||
${downgrades if downgrades else "pass"}
|
|
@ -0,0 +1,39 @@
|
|||
"""empty message
|
||||
|
||||
Revision ID: 81150b570cd1
|
||||
Revises: None
|
||||
Create Date: 2016-03-05 17:57:23.477373
|
||||
|
||||
"""
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = '81150b570cd1'
|
||||
down_revision = None
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
def upgrade():
|
||||
### commands auto generated by Alembic - please adjust! ###
|
||||
op.create_table('blog_post',
|
||||
sa.Column('id', sa.Integer(), nullable=False),
|
||||
sa.Column('title', sa.String(length=250), nullable=True),
|
||||
sa.Column('slug', sa.String(length=250), nullable=True),
|
||||
sa.Column('date', sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column('content', sa.Text(), nullable=True),
|
||||
sa.Column('html', sa.Text(), nullable=True),
|
||||
sa.Column('draft', sa.Boolean(), nullable=True),
|
||||
sa.PrimaryKeyConstraint('id')
|
||||
)
|
||||
op.create_index(op.f('ix_blog_post_date'), 'blog_post', ['date'], unique=False)
|
||||
op.create_index(op.f('ix_blog_post_slug'), 'blog_post', ['slug'], unique=False)
|
||||
### end Alembic commands ###
|
||||
|
||||
|
||||
def downgrade():
|
||||
### commands auto generated by Alembic - please adjust! ###
|
||||
op.drop_index(op.f('ix_blog_post_slug'), table_name='blog_post')
|
||||
op.drop_index(op.f('ix_blog_post_date'), table_name='blog_post')
|
||||
op.drop_table('blog_post')
|
||||
### end Alembic commands ###
|
|
@ -6,6 +6,7 @@
|
|||
"devDependencies": {
|
||||
"gulp": "^3.9.0",
|
||||
"gulp-concat": "^2.6.0",
|
||||
"gulp-concat-css": "^2.2.0",
|
||||
"gulp-livereload": "^3.8.1",
|
||||
"gulp-minify-css": "^1.2.2",
|
||||
"gulp-sass": "^2.0.4",
|
||||
|
|
|
@ -3,4 +3,11 @@ Flask==0.10.1
|
|||
# MD
|
||||
markdown2==2.3.0
|
||||
# ORM
|
||||
peewee==2.7.4
|
||||
SQLAlchemy==1.0.12
|
||||
Flask-SQLAlchemy==2.1
|
||||
Flask-Migrate==1.8.0
|
||||
# Admin
|
||||
Flask-Admin==1.4.0
|
||||
Flask-CDN==1.4.0
|
||||
# Automation
|
||||
Flask-Script==2.0.5
|
||||
|
|
Loading…
Reference in New Issue