Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!./flaskvenv/bin/python
- # -*- coding: utf-8 -*-
- # python libs
- import os
- from uuid import uuid4
- # flask
- from config import app
- from flask import render_template, flash, request, url_for, redirect, session, send_from_directory, abort, send_file
- # hashing password
- from passlib.hash import sha256_crypt
- # forms
- from forms import RegistrationForm, AddEmployees, AddPost, UploadFile
- from werkzeug.utils import secure_filename
- # mysql
- from MySQLdb import escape_string as thwart # sql injection
- from dbconnect import connection
- # python
- import gc
- # user decorators
- from decorator import login_required, role_control
- from datetime import datetime
- # content
- from content import get_count_file, file_types, get_content, get_bday_employees
- ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','docx', 'doc'])
- def allowed_file(filename):
- return '.' in filename and \
- filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
- @app.route('/')
- def index():
- title = "Главная"
- c,conn = connection()
- c.execute("SELECT * FROM posts ORDER BY uid DESC LIMIT 0,10")
- return render_template('index.html', title=title, data=c, get_count_file=get_count_file, bday=get_bday_employees())
- @app.route('/personal/')
- @login_required
- def personal():
- title = "Профиль"
- c,conn = connection()
- c.execute("SELECT username, email, name, lastname, role FROM users WHERE username = %s", [thwart(session['username'])])
- data = c.fetchone()
- return render_template("user_info.html", title=title, data=data)
- @app.route('/emplist/')
- @login_required
- def emplist():
- title = "Список сотрудников"
- c,conn = connection()
- c.execute("SELECT * FROM employees")
- data = c
- return render_template("emplist.html", title=title, data=data)
- @app.route('/list/')
- def list():
- title = 'Файлы'
- return render_template("filelist.html", get_count_file=get_count_file, type=file_types, get_content=get_content, title=title)
- @app.route('/posts/')
- def posts():
- title = "Новости"
- data = ''
- c,conn = connection()
- c.execute("SELECT * FROM posts WHERE post_type = 'new' ORDER BY uid DESC LIMIT 0,10")
- news = c
- c.close()
- conn.close()
- b,a = connection()
- b.execute("SELECT * FROM posts WHERE post_type = 'not' ORDER BY uid DESC LIMIT 0,10")
- notify = b
- b.close()
- a.close()
- return render_template('posts.html', title=title, news=news, notify=notify)
- @app.route('/post/<hash>')
- def view_post(hash):
- c,conn = connection()
- c.execute("SELECT * FROM posts WHERE url = %s", [hash])
- data = c.fetchone()
- title = data[2]
- return render_template("view_post.html", data=data, title=title)
- @app.route('/file/<fileid>', methods=['POST','GET'])
- def get_file(fileid):
- c,conn = connection()
- c.execute("SELECT name FROM files WHERE hash = %s", [thwart(fileid)])
- name = c.fetchone()[0]
- c.close()
- conn.close()
- uploads = os.path.join(app.root_path, 'static/upload/', name)
- return send_file(uploads, attachment_filename=name)
- @app.route('/login/', methods=['GET', 'POST'])
- def login():
- title="Login"
- error=""
- try:
- c,conn = connection()
- if request.method == 'POST':
- data = c.execute("SELECT * FROM users WHERE username = (%s)",
- [thwart(request.form['username'])])
- data = c.fetchone()[2]
- if 'logged_in' in session:
- flash("You already auth")
- return redirect(url_for('index'))
- elif sha256_crypt.verify(request.form['password'], data) :
- session['logged_in'] = True
- session['username'] = request.form['username']
- flash("Вы вошли в систему")
- return redirect(url_for('index'))
- else:
- error = "Недопустимые учетные данные, повторите попытку"
- gc.collect()
- return render_template('login.html', title=title, error=error)
- except Exception as e:
- error = 'Недопустимые учетные данные, повторите попытку'
- return render_template('login.html', title=title, error=error)
- @app.route('/logout/')
- def logout():
- session.clear()
- flash("Вы вышли из системы")
- gc.collect()
- return redirect(url_for('index'))
- @app.route('/register/', methods=['GET','POST'])
- @login_required
- @role_control
- def register():
- try:
- error = ''
- title = "Register"
- form = RegistrationForm(request.form)
- if request.method == 'POST' and form.validate():
- username = form.username.data
- email = form.email.data
- password = sha256_crypt.encrypt((str(form.password.data)))
- name = form.name.data
- lastname = form.lastname.data
- role = form.role.data
- c,conn = connection()
- x = c.execute("SELECT * FROM users WHERE username = (%s)",
- [thwart(username)])
- if int(x) > 0:
- flash("The user already registered")
- return redirect(url_for("register"))
- else:
- c.execute("INSERT INTO users (username, password, email, name, lastname, role) VALUES (%s, %s, %s, %s, %s, %s)",
- [thwart(username), thwart(password), thwart(email), thwart(name), thwart(lastname), thwart(role)])
- conn.commit()
- flash("Пользователь добавлен!")
- c.close()
- conn.close()
- gc.collect()
- return redirect(url_for('index'))
- return render_template('register.html', title=title, form=form, error=error)
- except Exception as e:
- return(str(e))
- @app.route('/employees/', methods=['GET','POST'])
- @login_required
- def add_employees():
- try:
- title = "Добавить сотрудников"
- form = AddEmployees(request.form)
- if request.method == 'POST':
- name = form.name.data
- lastname = form.lastname.data
- dep = form.dep.data
- bday = form.bday.data
- c, conn = connection()
- c.execute("INSERT INTO employees (name, lastname,dep, bday) VALUES (%s, %s, %s, %s)",
- [thwart(name), thwart(lastname), thwart(dep), thwart(bday)])
- conn.commit()
- flash("Добавлен сотрудник")
- c.close()
- conn.close()
- return redirect(url_for('index'))
- return render_template('add_employees.html', title=title, form=form)
- except Exception as e:
- return(str(e))
- @app.route('/post/', methods=['GET', 'POST'])
- @login_required
- def add_post():
- try:
- title = "Добавить новости"
- form = AddPost(request.form)
- if request.method == 'POST':
- post_type = form.post_type.data.encode('utf-8').decode()
- subject = form.subject.data.encode('utf-8').decode()
- full_text = form.full_text.data.encode('utf-8').decode()
- c,conn = connection()
- c.execute("INSERT INTO posts (post_type, subject, full_text, url) VALUES (%s, %s, %s, %s)",
- [thwart(post_type), thwart(subject), thwart(full_text), thwart(str(uuid4()))])
- conn.commit()
- flash("Добвален пост")
- c.close()
- conn.close()
- return redirect(url_for('index'))
- return render_template('add_post.html', title=title, form=form)
- except Exception as e:
- return(str(e))
- @app.route('/upload/', methods=['GET', 'POST'])
- @login_required
- def upload():
- title = "Добавить файлы"
- form = UploadFile(request.form)
- if request.method == 'POST':
- if 'file' not in request.files:
- flash("No file part")
- return redirect(request.url)
- file = request.files['file']
- if file.filename == '':
- flash("No selected file")
- return redirect(request.url)
- if file and allowed_file(file.filename):
- file_type = form.file_parent.data
- # filename = secure_filename(file.filename)
- filename = file.filename
- print(filename)
- file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
- c,conn = connection()
- c.execute("INSERT INTO files (name, url, hash, file_type) VALUES (%s, %s, %s, %s)",
- [thwart(filename),thwart(app.config['UPLOAD_FOLDER'] + '/' + filename),thwart(str(uuid4())),thwart(file_type)])
- conn.commit()
- c.close()
- conn.close()
- flash("Файл добавлен")
- return redirect(url_for('upload'))
- return render_template('add_file.html',title=title)
- @app.route('/check/')
- def check():
- return '''Check page
- '''
- # error handlers
- @app.errorhandler(404)
- def page_not_found(e):
- error = "404: Страница не найдена"
- return render_template("fail.html", error=error)
- if __name__ == "__main__":
- app.run(debug=True, host='0.0.0.0')
Add Comment
Please, Sign In to add comment