Advertisement
Guest User

Untitled

a guest
Jul 19th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.83 KB | None | 0 0
  1. from functools import wraps
  2. from flask import Flask, abort, render_template, flash, url_for, redirect, request, session, Response
  3. from flaskext.sqlalchemy import SQLAlchemy
  4. from wtforms import Form, TextField, TextAreaField, IntegerField, SelectField, validators
  5.  
  6. # INITIALISE FLASK
  7. app = Flask(__name__)
  8. app.config.from_pyfile('config.cfg')
  9.  
  10.  
  11. # DEFINE MODEL(S)
  12. db = SQLAlchemy(app)
  13.  
  14. class Page(db.Model):
  15.     __tablename__ = 'pages'
  16.     id          = db.Column(db.Integer, primary_key=True)
  17.     title       = db.Column(db.String(100), nullable=False)
  18.     content     = db.Column(db.Text, nullable=False)
  19.     parent_id   = db.Column(db.Integer, db.ForeignKey("pages.id"), nullable=True)
  20.     children    = db.relationship("Page", backref=db.backref("parent", remote_side=id))
  21.    
  22.     def __init__(self, title, content, parent_id=None):
  23.         self.title = title
  24.         self.content = content
  25.         if parent_id:
  26.             self.parent_id = parent_id
  27.    
  28.     def __repr__(self):
  29.         return '<Page "%r">' % self.title
  30.  
  31.  
  32. # DEFINE FORMS
  33. class PageForm(Form):
  34.     title   = TextField('Page Title', validators=[validators.Required()])
  35.     content = TextAreaField('Page Content', validators=[validators.Required()])
  36.     parent  = IntegerField('Parent Page ID (optional)', validators=[validators.optional()])
  37.     #parent  = SelectField('Parent Page (Optional)', coerce=int)
  38.  
  39.  
  40. # DISPLAY FUNCTIONS
  41. @app.errorhandler(404)
  42. def page_not_found(error):
  43.     return render_template('404.html'), 404
  44.  
  45. @app.route('/')
  46. def list_pages():
  47.     '''Grab all top level pages and display them'''
  48.     pages = Page.query.filter_by(parent_id=None)
  49.     return render_template('list_pages.html', pages=pages)
  50.  
  51. @app.route('/<int:page_id>')
  52. def display_page(page_id):
  53.     '''Get the page content and it's children and
  54.    display them
  55.    '''
  56.     page = Page.query.get(page_id)
  57.     if not page:
  58.         abort(404)
  59.     title = page.title
  60.     content = page.content
  61.     sub_pages = Page.query.filter_by(parent_id=page_id)
  62.     return render_template('page.html', title=title,
  63.                            content=content, sub_pages=sub_pages)
  64.  
  65.  
  66. # ADMIN HEPER FUNCTIONS
  67. def check_auth(username, password):
  68.     """This function is called to check if a username /
  69.    password combination is valid.
  70.    """
  71.     return username == app.config['USERNAME'] and password == app.config['PASSWORD']
  72.  
  73. def authenticate():
  74.     """Sends a 401 response that enables basic auth"""
  75.     return Response(
  76.     'Could not verify your access level for that URL.\n'
  77.     'You have to login with proper credentials', 401,
  78.     {'WWW-Authenticate': 'Basic realm="Login Required"'})
  79.  
  80. def requires_auth(f):
  81.     @wraps(f)
  82.     def decorated(*args, **kwargs):
  83.         auth = request.authorization
  84.         if not auth or not check_auth(auth.username, auth.password):
  85.             return authenticate()
  86.         return f(*args, **kwargs)
  87.     return decorated
  88.  
  89.  
  90. #ADMIN FUNCTIONS
  91. @app.route('/admin/')
  92. @requires_auth
  93. def admin_page():
  94.     '''Grab all pages and list so user can edit'''
  95.     pages = Page.query.all()
  96.     if not pages:
  97.         return render_template('down.html')
  98.     return render_template('admin_home.html', pages=pages)
  99.  
  100. @app.route('/admin/new/', methods=['GET','POST'])
  101. @requires_auth
  102. def new_page():
  103.     '''Display edit form and add all data from submitted
  104.    forms into the database'''
  105.     form = PageForm(request.form)
  106.     if request.method == 'POST' and form.validate():
  107.         page = Page(form.title.data, form.content.data, form.parent.data)
  108.         db.session.add(page)
  109.         if db.session.commit():
  110.             flash('Page was added successfully', 'success')
  111.         else:
  112.             flash('There was an error when inserting the page into the database',
  113.                   'error')
  114.         return redirect(url_for('list_pages'))
  115.     return render_template('admin_new.html', form=form)
  116.  
  117. @app.route('/admin/edit/<int:page_id>', methods=['GET','POST'])
  118. @requires_auth
  119. def edit_page(page_id):
  120.     '''Grab data for the specified page and insert into the
  121.    form, then grab the submitted form and update the page
  122.    '''
  123.     page = Page.query.get(page_id)
  124.     if not page:
  125.         abort(404)
  126.     form = PageForm(request.form)
  127.     if request.method == 'POST' and form.validate():
  128.         page = Page(form.title.data, form.content.data, form.parent.data)
  129.         if db.session.commit():
  130.             flash('Page was edited successfully', 'success')
  131.         else:
  132.             flash('There was an error when updating the page in the database',
  133.                   'error')
  134.         return redirect(url_for('list_pages'))
  135.     form.title.data = page.title
  136.     form.content.data = page.content
  137.     form.parent.data = page.parent_id
  138.     return render_template('admin_edit.html', form=form, page_edit_id=page_id)
  139.  
  140. # RUN APP
  141. if __name__ == '__main__':
  142.     app.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement