Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from functools import wraps
- from flask import Flask, abort, render_template, flash, url_for, redirect, request, session, Response
- from flaskext.sqlalchemy import SQLAlchemy
- from wtforms import Form, TextField, TextAreaField, IntegerField, SelectField, validators
- # INITIALISE FLASK
- app = Flask(__name__)
- app.config.from_pyfile('config.cfg')
- # DEFINE MODEL(S)
- db = SQLAlchemy(app)
- class Page(db.Model):
- __tablename__ = 'pages'
- id = db.Column(db.Integer, primary_key=True)
- title = db.Column(db.String(100), nullable=False)
- content = db.Column(db.Text, nullable=False)
- parent_id = db.Column(db.Integer, db.ForeignKey("pages.id"), nullable=True)
- children = db.relationship("Page", backref=db.backref("parent", remote_side=id))
- def __init__(self, title, content, parent_id=None):
- self.title = title
- self.content = content
- if parent_id:
- self.parent_id = parent_id
- def __repr__(self):
- return '<Page "%r">' % self.title
- # DEFINE FORMS
- class PageForm(Form):
- title = TextField('Page Title', validators=[validators.Required()])
- content = TextAreaField('Page Content', validators=[validators.Required()])
- parent = IntegerField('Parent Page ID (optional)', validators=[validators.optional()])
- #parent = SelectField('Parent Page (Optional)', coerce=int)
- # DISPLAY FUNCTIONS
- @app.errorhandler(404)
- def page_not_found(error):
- return render_template('404.html'), 404
- @app.route('/')
- def list_pages():
- '''Grab all top level pages and display them'''
- pages = Page.query.filter_by(parent_id=None)
- return render_template('list_pages.html', pages=pages)
- @app.route('/<int:page_id>')
- def display_page(page_id):
- '''Get the page content and it's children and
- display them
- '''
- page = Page.query.get(page_id)
- if not page:
- abort(404)
- title = page.title
- content = page.content
- sub_pages = Page.query.filter_by(parent_id=page_id)
- return render_template('page.html', title=title,
- content=content, sub_pages=sub_pages)
- # ADMIN HEPER FUNCTIONS
- def check_auth(username, password):
- """This function is called to check if a username /
- password combination is valid.
- """
- return username == app.config['USERNAME'] and password == app.config['PASSWORD']
- def authenticate():
- """Sends a 401 response that enables basic auth"""
- return Response(
- 'Could not verify your access level for that URL.\n'
- 'You have to login with proper credentials', 401,
- {'WWW-Authenticate': 'Basic realm="Login Required"'})
- def requires_auth(f):
- @wraps(f)
- def decorated(*args, **kwargs):
- auth = request.authorization
- if not auth or not check_auth(auth.username, auth.password):
- return authenticate()
- return f(*args, **kwargs)
- return decorated
- #ADMIN FUNCTIONS
- @app.route('/admin/')
- @requires_auth
- def admin_page():
- '''Grab all pages and list so user can edit'''
- pages = Page.query.all()
- if not pages:
- return render_template('down.html')
- return render_template('admin_home.html', pages=pages)
- @app.route('/admin/new/', methods=['GET','POST'])
- @requires_auth
- def new_page():
- '''Display edit form and add all data from submitted
- forms into the database'''
- form = PageForm(request.form)
- if request.method == 'POST' and form.validate():
- page = Page(form.title.data, form.content.data, form.parent.data)
- db.session.add(page)
- if db.session.commit():
- flash('Page was added successfully', 'success')
- else:
- flash('There was an error when inserting the page into the database',
- 'error')
- return redirect(url_for('list_pages'))
- return render_template('admin_new.html', form=form)
- @app.route('/admin/edit/<int:page_id>', methods=['GET','POST'])
- @requires_auth
- def edit_page(page_id):
- '''Grab data for the specified page and insert into the
- form, then grab the submitted form and update the page
- '''
- page = Page.query.get(page_id)
- if not page:
- abort(404)
- form = PageForm(request.form)
- if request.method == 'POST' and form.validate():
- page = Page(form.title.data, form.content.data, form.parent.data)
- if db.session.commit():
- flash('Page was edited successfully', 'success')
- else:
- flash('There was an error when updating the page in the database',
- 'error')
- return redirect(url_for('list_pages'))
- form.title.data = page.title
- form.content.data = page.content
- form.parent.data = page.parent_id
- return render_template('admin_edit.html', form=form, page_edit_id=page_id)
- # RUN APP
- if __name__ == '__main__':
- app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement