Файл: азастан Республикасы ылым жне жоары білім министрлігі лФараби атындаы аза лтты университеті.docx

ВУЗ: Не указан

Категория: Дипломная работа

Дисциплина: Не указана

Добавлен: 02.12.2023

Просмотров: 154

Скачиваний: 2

ВНИМАНИЕ! Если данный файл нарушает Ваши авторские права, то обязательно сообщите нам.

ҚОСЫМША А


«Server.py» файл листингі
import json

import os

from decimal import Decimal

from pydoc import locate

from cache import cache

from threading import Thread

import requests

from flask import (Flask, Response, jsonify, make_response, redirect,

render_template, request, send_file, send_from_directory,

session, url_for)

from flask_httpauth import HTTPBasicAuth

from flask_login import (LoginManager, UserMixin, current_user, login_required,

login_user, logout_user)

from flask_socketio import SocketIO, join_room, leave_room

from sqlalchemy import create_engine

from sqlalchemy.ext.declarative import declarative_base

from sqlalchemy.orm import (Query, backref, relationship, scoped_session,

sessionmaker)

from werkzeug.security import check_password_hash, generate_password_hash

from app_code.encoder import CustomJsonEncoder

from container import Charts, Provider, Reader

from controllers.history import history_controller

from controllers.data import data_controller

from controllers.cases import cases_controller

from controllers.chart import chart_controller

from models.user import User, UserProvider

server = '127.0.0.1'

port = 3010

signin_url = 'http://%s:%s/signin' % (server, port)

app = Flask(__name__,

static_folder='./templates/public',

template_folder="./templates/static")

cache.init_app(app)

with open('config.json', encoding='utf-8') as config:

app.config['DATA'] = json.load(config)

app.register_blueprint(history_controller, url_prefix="/history")

app.register_blueprint(data_controller, url_prefix="/api")

app.register_blueprint(cases_controller, url_prefix="/cases")

app.register_blueprint(chart_controller, url_prefix="/api")
app.json_encoder = CustomJsonEncoder

app.config['SECRET_KEY'] = 'q1w2e3r4#'

app.config['JSON_AS_ASCII'] = False

lg = LoginManager(app)

lg.login_view = signin_url

socketio = SocketIO(app, cors_allowed_origins="*",

async_mode='threading')
Provider.config.override(app.config['DATA']['db'])

ContainerCharts = Charts()

Users = UserProvider.get_users()

@lg.user_loader

def user_loader(id):

user = next(x for x in Users if x.id == int(id))

return user

@app.route('/favicon.ico')

def favicon():

return send_from_directory(os.path.join(app.root_path, './templates/static'),

'favicon.ico', mimetype='image/vnd.microsoft.icon')

@app.route('/signin', methods=['GET', 'POST'])

def signin():

if request.method == 'POST':

data = request.json

if data['username'] is not None:

username = data['username'].lower()

password = data['password']

user = next(x for x in Users if x.login.lower() == username)

if user:

if check_password_hash(user.password, password):

login_user(user)

return jsonify({

'signin': True

})
return jsonify({

'signin': False

})

return render_template('login.html')

@app.route('/signout', methods=['GET', 'POST'])

def signout():

if current_user.is_authenticated:

logout_user()

return redirect(signin_url)

return redirect(url_for('index'))
@app.route('/')

@app.route('/index')

@login_required

def index():

if (current_user.is_authenticated):

return render_template('index.html', username=current_user.display_name)

return redirect(url_for('signin'))
@app.route('/data', defaults={'category': 'empty'})

@app.route('/data/')

@login_required

@cache.cached(timeout=10)

def charts(category):

try:

data = app.config['DATA'][category]

return jsonify(data)

except:

pass

return jsonify(None)
if __name__ == '__main__':
table_name = app.config['DATA']["reports"]["table_name"]

default_columns = app.config['DATA']["reports"]["default_columns"]
reader = Reader()

reader.config.override({

"DEFAULT_COLUNMS": default_columns

})

app.config['READER'] = reader.db_class()

relations = app.config['READER'].get_fk(table_name)
app.config['TABLE_CORE'] = table_name

app.config['DATA']["reports"]["fields"] = app.config['READER'].get_table_info(

table_name, relations)

app.config["TEMPLATES_AUTO_RELOAD"] = True

socketio.run(app, host=server, port=port, debug=False)