Commit ae07a372 authored by tair@local's avatar tair@local
Browse files

first

parent 62e3d12e
Pipeline #2158 failed with stages
DEBUG=true
SECRET_KEY=some_key
SQLALCHEMY_DATABASE_URI=data.sqlite3
/venv/
/.idea/
# Flask stuff:
instance/
.webassets-cache
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
\ No newline at end of file
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_cors import CORS
from app.site.routes import site
from app.api.routes import api
bootstrap = Bootstrap()
def create_app(config_name, db):
# create app instance
app = Flask(__name__,static_folder='./site/dist',
template_folder='./site/dist',
static_url_path='')
CORS(app)
# add configuration
app.config.from_object(config_name)
# register extensions
bootstrap.init_app(app)
db.app = app
db.init_app(app)
# register blueprints
app.register_blueprint(site)
app.register_blueprint(api, url_prefix='/api')
return app
"""
first, import db to setup app context
from run import db
then, import model to use it with queries
from app.models import User
"""
from flask import Blueprint
api = Blueprint('api', __name__)
from flask import jsonify, request, abort, make_response, current_app
from . import api
from app.api.step1 import blocksinfo,analysis,schemeaction
# custom 404 error handler
@api.errorhandler(404)
def not_found(error):
return make_response(jsonify({'detail': 'Not found'}), 404)
# custom 400 error handler
@api.errorhandler(400)
def bad_request(error):
return make_response(jsonify({'detail': 'Bad request'}), 400)
# получить список доступных блоков для редактора
@api.route('/getallblocks', methods=['GET'])
def getallblocks():
return jsonify(blocksinfo.all())
@api.route('/getblockinfo/<name>', methods=['GET'])
def getblockinfo(name):
return jsonify(blocksinfo.blockdetails(name))
@api.route('/process', methods=['POST'])
def doprocess():
dict_data = request.json
return jsonify(analysis.process(dict_data))
@api.route('/loadscheme/demo', methods=['GET'])
def doload():
return jsonify(schemeaction.load())
import json
def process(jdata):
print(jdata)
print(json.dumps(jdata)) # Flask сам возращает dict из json. Это просто пример.
print(type(jdata))
print(jdata['nodes'][0]['func'])
# Обработка схемы
# ...
# Пример ответа на запрос, по данному ответу будет показан график или popup с ошибкой
example_result = {
#--- обязательно нужно вернуть результат операции
"result" : "success", # success | error | warning
"errortext" : "none", # указывается ошибка или none
#--- если ошибка chart можно не включать
"chart" : [{
"name": "series-1",
"data": [1, 3, 4, 3, 2.5, 1, 0.5, 0.3]
},
{
"name": "series-2",
"data": [1, 2, 3, 2, 2, 0.8, 0.3, 2]
}]
}
return example_result
def all():
# Список блоков которые можно добавить в редактор
a = [{
"func": "generator",
"defparam": "turbogenerator",
"name": "Синхронный генератор",
"descr": "Краткое описание объекта",
"ico" : "turbine1",
"type": "operation",
},
{
"func": "transformator",
"defparam": "default",
"name": "Трансформатор",
"descr": "Краткое описание объекта",
"ico": "powerplug",
"type": "operation",
},
{
"func": "powerline",
"defparam": "airline",
"name": "Линия электропередачи",
"descr": "Краткое описание объекта",
"ico": "powerline",
"type": "end",
},
{
"func": "infintebus",
"defparam": "default",
"name": "Шина беск. мощности",
"descr": "Краткое описание объекта",
"ico": "power",
"type": "operation",
},
{
"func": "excitationsystem",
"defparam": "electromachine",
"name": "Сист. возбуждения",
"descr": "Краткое описание объекта",
"ico": "powerline2",
"type": "operation",
},
{
"func": "arv",
"defparam": "electromachine",
"name": "АРВ",
"descr": "Краткое описание объекта",
"ico": "powerwarn",
"type": "start",
}
]
# TODO: генерить из метеданных файлов-функций
return a
def blockdetails(name):
# Описание и параметры (двойной клик по блоку)
b = {
"generator" : { # берется из параметра func
"params": ["param1","param2"],
"features": [{"feature1":"value1"},{"feature2":"value2"}]
},
"arv": {
"params": ["paramPSS1", "paramPSS2"],
"features": [{"featurePSS1": "value1"}, {"featurePSS2": "value2"}]
},
}
return b[name]
def save():
#TODO: save to sql
return ""
def load():
# TODO: load from sql
demo1 = {
"nodes": [
{
"id": 1624188947463,
"x": 110, # неважно для расчетов
"y": 100, # неважно для расчетов
"func": "arv",
"param": "electromachine",
"type": "start",
"name": "АРВ", # неважно для расчетов
"ico": "powerwarn",# неважно для расчетов
"width": 240, # неважно для расчетов
"height": 90 # неважно для расчетов
},
{
"id": 1624188962684,
"x": 110,
"y": 240,
"func": "generator",
"param": "turbogenerator",
"type": "operation",
"name": "Синхронный генератор",
"ico": "turbine1",
"width": 240,
"height": 90
},
{
"id": 1624188971460,
"x": 460,
"y": 310,
"func": "transformator",
"param": "default",
"type": "operation",
"name": "Трансформатор",
"ico": "powerplug",
"width": 240,
"height": 90
}
],
"connections": [
{
"source": {
"id": 1624188947463,
"position": "bottom"
},
"destination": {
"id": 1624188962684,
"position": "top"
},
"id": 1624188986951,
"type": "pass",
"name": "Pass"
},
{
"source": {
"id": 1624188962684,
"position": "right"
},
"destination": {
"id": 1624188971460,
"position": "left"
},
"id": 1624188996602,
"type": "pass", # неважно, можно подсвечивать красным если найдена ошибка 'fail'
"name": "Pass" # неважно, можно добавить дополнительное свойство соединительной линии
}
]
}
return demo1
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import Required, Length, Optional
from wtforms.widgets import TextArea
class NameForm(FlaskForm):
name = StringField(
'Add user name:', validators=[Required(), Length(1, 16)])
description = StringField(
'Short description', widget=TextArea(),
validators=[Optional(), Length(max=200)])
submit = SubmitField('Submit')
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
# Для сохранения готовых схем
class Schemes(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), index=True, unique=True)
scheme = db.Column(db.String(200))
def __repr__(self):
return '<Scheme {0}>'.format(self.name)
def serialize(self):
"""
Custom method used within api to serialize database objects into
JSON.
"""
return {
'id': self.id,
'name': self.name,
'scheme': self.scheme,
}
# Для пользователей - пока не используется
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(16), index=True, unique=True)
description = db.Column(db.String(200))
pwd = db.Column(db.String(200))
def __repr__(self):
return '<User {0}>'.format(self.name)
def serialize(self):
"""
Custom method used within api to serialize database objects into
JSON.
"""
return {
'id': self.id,
'name': self.name,
'description': self.description,
'pwd': self.pwd,
}
from flask import Blueprint
site = Blueprint('site', __name__,template_folder='templates')
This diff is collapsed.
@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:100;src:local("Roboto Thin "),local("Roboto-Thin"),url(../fonts/roboto-latin-100.7370c367.woff2) format("woff2"),url(../fonts/roboto-latin-100.5cb7edfc.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:100;src:local("Roboto Thin italic"),local("Roboto-Thinitalic"),url(../fonts/roboto-latin-100italic.f8b1df51.woff2) format("woff2"),url(../fonts/roboto-latin-100italic.f9e8e590.woff) format("woff")}@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:300;src:local("Roboto Light "),local("Roboto-Light"),url(../fonts/roboto-latin-300.ef7c6637.woff2) format("woff2"),url(../fonts/roboto-latin-300.b00849e0.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:300;src:local("Roboto Light italic"),local("Roboto-Lightitalic"),url(../fonts/roboto-latin-300italic.14286f3b.woff2) format("woff2"),url(../fonts/roboto-latin-300italic.4df32891.woff) format("woff")}@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:400;src:local("Roboto Regular "),local("Roboto-Regular"),url(../fonts/roboto-latin-400.479970ff.woff2) format("woff2"),url(../fonts/roboto-latin-400.60fa3c06.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:400;src:local("Roboto Regular italic"),local("Roboto-Regularitalic"),url(../fonts/roboto-latin-400italic.51521a2a.woff2) format("woff2"),url(../fonts/roboto-latin-400italic.fe65b833.woff) format("woff")}@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:500;src:local("Roboto Medium "),local("Roboto-Medium"),url(../fonts/roboto-latin-500.020c97dc.woff2) format("woff2"),url(../fonts/roboto-latin-500.87284894.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:500;src:local("Roboto Medium italic"),local("Roboto-Mediumitalic"),url(../fonts/roboto-latin-500italic.db4a2a23.woff2) format("woff2"),url(../fonts/roboto-latin-500italic.288ad9c6.woff) format("woff")}@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:700;src:local("Roboto Bold "),local("Roboto-Bold"),url(../fonts/roboto-latin-700.2735a3a6.woff2) format("woff2"),url(../fonts/roboto-latin-700.adcde98f.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:700;src:local("Roboto Bold italic"),local("Roboto-Bolditalic"),url(../fonts/roboto-latin-700italic.da0e7178.woff2) format("woff2"),url(../fonts/roboto-latin-700italic.81f57861.woff) format("woff")}@font-face{font-family:Roboto;font-style:normal;font-display:swap;font-weight:900;src:local("Roboto Black "),local("Roboto-Black"),url(../fonts/roboto-latin-900.9b3766ef.woff2) format("woff2"),url(../fonts/roboto-latin-900.bb1e4dc6.woff) format("woff")}@font-face{font-family:Roboto;font-style:italic;font-display:swap;font-weight:900;src:local("Roboto Black italic"),local("Roboto-Blackitalic"),url(../fonts/roboto-latin-900italic.ebf6d164.woff2) format("woff2"),url(../fonts/roboto-latin-900italic.28f91510.woff) format("woff")}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment