A small revolution with forms and routes ! need to redo all the classes and models so that their articles have exactly the same name and then it will implement itself

master
Kerem Yollu 10 months ago
parent 9e30d68422
commit 64cf31f939

139
web/2

@ -1,139 +0,0 @@
from flask import render_template, Blueprint, request, flash, redirect, url_for
import minibase.theme as theme
from minibase.blueprints.sensor.models import nbiotDevice
import minibase.blueprints.sensor.utils as sensorUtils
from minibase.blueprints.sensor.forms import updateNbioDeviceUpdateForm, updateNbioDeviceAddForm
import minibase.blueprints.database.utils as dbUtils
import minibase.blueprints.company.utils as companyUtils
import minibase.blueprints.user.utils as userUtils
from minibase.app import db
import json
import os
sensor = Blueprint('sensor', __name__, template_folder='templates')
DATA_FILE = 'data.json'
sensor.route('/callback', methods=['POST'])
def callback():
data = request.json
if not data:
return jsonify({"error": "Invalid data"}), 400
# Read existing data
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
stored_data = json.load(f)
else:
stored_data = []
# Append new data
stored_data.append(data)
# Write data back to file
with open(DATA_FILE, 'w') as f:
json.dump(stored_data, f, indent=4)
return 'Callback received', 200
@sensor.route('/data', methods=['GET'])
def get_data():
if os.path.exists(DATA_FILE):
with open(DATA_FILE, 'r') as f:
stored_data = json.load(f)
else:
stored_data = []
return jsonify(stored_data)
@sensor.route('/list', methods=['GET','POST'])
def list():
page=request.args.get('page', 1, type=int)
table=dbUtils.table_printable_paginate(nbiotDevice, page, 20, 'edit/', 'id')
return(render_template('view.html', theme=theme, table=table, title="Devices List"))
@sensor.route("/edit/<int:deviceId>", methods=['GET', 'POST'])
def edit(deviceId):
if deviceId:
device = nbiotDevice.query.get_or_404(deviceId)
form = updateNbioDeviceUpdateForm(current_device_id=device.id)
form.user_id.choices = [(row.id, row.username) for row in userUtils.queryUserNamesWithDefault(device.user_id)]
form.owner_id.choices = [(row.id, row.username) for row in userUtils.queryUserNamesWithDefault(device.user_id)]
form.manufacturer_id.choices = [(row.id, row.name) for row in companyUtils.queryNamesWithDefault(device.manufacturer_id)]
form.company_id.choices = [(row.id, row.name) for row in companyUtils.queryNamesWithDefault(device.company_id)]
form.status_id.choices = [(row.id, row.name) for row in sensorUtils.queryStatusNamesWithDefault(device.status_id)]
form.type_id.choices = [(row.id, row.name) for row in sensorUtils.queryTypeNamesWithDefault(device.type_id)]
form.area_id.choices = [(row.id, row.name) for row in sensorUtils.queryAreaNamesWithDefault(device.area_id)]
if form.validate_on_submit():
device.name=form.name.data
device.serial_no = form.serial_no.data
device.device_id=form.device_id.data
device.imsi=form.imsi.data
device.iccid=form.iccid.data
device.ip=form.ip.data
device.port=form.port.data
device.registration_date=form.registration_date.data
device.activation_date=form.activation_date.data
device.deactivation_date=form.deactivation_date.data
device.owner_id=form.owner_id.data
device.user_id=form.user_id.data
device.status_id=form.status_id.data
device.type_id=form.type_id.data
device.area_id=form.area_id.data
device.manufacturer_id = form.manufacturer_id.data
device.company_id = form.manufacturer_id.data
db.session.commit()
flash('Device has been successfully updated', 'success')
return redirect(url_for('sensor.edit', deviceId=deviceId))
elif request.method == 'GET':
form.name.data = device.name
form.serial_no.data = device.serial_no
form.device_id.data = device.device_id
form.imsi.data = device.imsi
form.iccid.data = device.iccid
form.ip.data = device.ip
form.port.data = device.port
form.registration_date.data = device.registration_date
form.activation_date.data = device.activation_date
form.deactivation_date.data = device.deactivation_date
return render_template('sensor/account.html',
theme=theme,
form=form)
else:
flash('You need to select a Device id', 'alarm')
return redirect(url_for('sensor.list'))
@sensor.route('/add', methods=['GET', 'POST'])
def add():
form = updateNbioDeviceAddForm()
form.user_id.choices = [(row.id, row.username) for row in userUtils.queryUserChoices(1)]
form.status_id.choices = [(row.id, row.name) for row in sensorUtils.queryStatusChoices(1)]
form.type_id.choices = [(row.id, row.name) for row in sensorUtils.queryTypeChoices(1)]
form.area_id.choices = [(row.id, row.name) for row in sensorUtils.queryAreaChoices(1)]
if form.validate_on_submit():
dev = nbiotDevice(
name=form.name.data,
device_id=form.device_id.data,
imsi=form.imsi.data,
iccid=form.iccid.data,
ip=form.ip.data,
port=form.port.data,
registration_date=form.registration_date.data,
activation_date=form.activation_date.data,
deactivation_date=form.deactivation_date.data,
user_id=form.user_id.data,
status_id=form.status_id.data,
type_id=form.type_id.data,
area_id=form.area_id.data)
dbUtils.dbAddAndCommit(dev)
flash('Device has been successfully added', 'success')
return render_template('sensor/account.html',
theme=theme,
form=form)

Binary file not shown.

@ -3,29 +3,52 @@ from flask_wtf.file import FileField, FileAllowed
from wtforms import StringField, SubmitField, URLField, IntegerField, SelectField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
import minibase.blueprints.company.utils as companyUtils
import minibase.blueprints.geography.utils as geoUtils
import minibase.blueprints.main.utils as mainUtils
import minibase.theme as theme
from wtforms_alchemy import ModelForm
from minibase.blueprints.company.models import Companies
from minibase.blueprints.sensor.models import nbiotDevice
from minibase.blueprints.user.models import Users
class updateCompanyForm(FlaskForm): # Defines the form class to be used for the user update
name = StringField('Name', validators=[DataRequired(), Length(min=3, max=100)])
website = URLField('Website', validators=[DataRequired(), Length(min=3, max=100)])
country = SelectField('Country', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_cities", "hx-target": "#city"})
city = SelectField('City', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_states", "hx-target": "#state"})
state = SelectField('State', validators=[])
country_id = SelectField('Country', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_cities", "hx-target": "#city_id"})
city_id = SelectField('City', validators=[DataRequired()], render_kw={"hx-get": "/geography/get_states", "hx-target": "#state_id"})
state_id = SelectField('State', validators=[])
post_code = IntegerField('Post', validators=[DataRequired()])
street = StringField('Street', validators=[DataRequired()])
street_no = IntegerField('No', validators=[DataRequired()])
industry = SelectField('Industry', validators=[DataRequired()])
legal_entity= SelectField('Legal Entity', validators=[DataRequired()])
type = SelectField('Type', validators=[DataRequired()])
relation = SelectField('Relation', validators=[DataRequired()])
status = SelectField('Status', validators=[DataRequired()])
industry_id = SelectField('Industry', validators=[DataRequired()])
legal_entity_id = SelectField('Legal Entity', validators=[DataRequired()])
type_id = SelectField('Type', validators=[DataRequired()])
relation_id = SelectField('Relation', validators=[DataRequired()])
status_id = SelectField('Status', validators=[DataRequired()])
comment = StringField('Comment', validators=[DataRequired(), Length(min=3, max=400)])
picture = FileField('Update company Picture', validators=[FileAllowed(['jpg', 'png'])])
image_file = FileField('Update company Picture', validators=[FileAllowed(['jpg', 'png'])])
submit = SubmitField('Update')
def populate_choices(self, company):
self.country_id.choices = [(row.id, row.name) for row in geoUtils.queryCountryNamesWithDefault(company.country_id)]
# This is for the htmx implementation. please be careful how of there is data we first take from the database an then from the from(containing th htmx call)
if self.country_id.data:
self.city_id.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryId(self.country_id.data)]
self.state_id.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryId(self.country_id.data)]
else:
self.city_id.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryIdWithDefault(company.city_id, company.country_id)]
self.state_id.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryIdWithDefault(company.state_id, company.country_id)]
self.industry_id.choices = [(row.id, row.name) for row in mainUtils.queryIndustryNamesWithDefault(company.industry_id)]
self.legal_entity_id.choices = [(row.id, row.name) for row in companyUtils.queryLegalEntityNamesWithDefault(company.legal_entity_id)]
self.type_id.choices = [(row.id, row.name) for row in companyUtils.queryTypeNamesWithDefault(company.type_id)]
self.relation_id.choices = [(row.id, row.name) for row in companyUtils.queryRelationNamesWithDefault(company.relation_id)]
self.status_id.choices = [(row.id, row.name) for row in companyUtils.queryStatusNamesWithDefault(company.status_id)]
# Queries to be made in order to validate the form : If username exists
def validate_companyName(self, company_name):
company = companyUtils.queryByNameFirst(company_name)

@ -6,7 +6,12 @@ from minibase.blueprints.main.models import Industries, Notes
class Companies(db.Model):
__tablename__ = 'companies'
#Auto Fiels
id = db.Column(db.Integer, nullable=False, primary_key=True)
upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
last_update_date= db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
#Own Fields
name = db.Column(db.String(100), nullable=False)
website = db.Column(db.String(100), nullable=True, default='')
street = db.Column(db.String(100), nullable=False)
@ -14,9 +19,9 @@ class Companies(db.Model):
post_code = db.Column(db.Integer, nullable=False)
comment = db.Column(db.String(300), nullable=True)
image_file = db.Column(db.String(20), nullable=False, default='def_company_avatar.png')
upload_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow)
last_update_date = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
#RELATIONSHIPS
# One To Many Relationship
legal_entity_id = db.Column(db.Integer, db.ForeignKey('company_legal_entities.id'), nullable=False)
type_id = db.Column(db.Integer, db.ForeignKey('company_types.id'), nullable=False)
@ -30,7 +35,7 @@ class Companies(db.Model):
# Many To one
notes = db.relationship('Notes', backref='company_notes', lazy='dynamic')
# Relationships to Device
# to Device
manufactured_devices= db.relationship("nbiotDevice", foreign_keys="nbiotDevice.company_manufacturer_id", back_populates="company_manufacturer")
owned_devices = db.relationship("nbiotDevice", foreign_keys="nbiotDevice.company_owner_id", back_populates="company_owner")

@ -26,56 +26,23 @@ def account(companyId):
company = Companies.query.get_or_404(companyId)
form = updateCompanyForm()
form.country.choices = [(row.id, row.name) for row in geoUtils.queryCountryNamesWithDefault(company.country_id)]
# This is for the htmx implementation. please be careful how of there is data we switch the funtion needed
if form.country.data:
form.city.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryId(form.country.data)]
form.state.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryId(form.country.data)]
else:
form.city.choices = [(row.id, row.name) for row in geoUtils.queryCityNamesWithCountryIdWithDefault(company.city_id, company.country_id)]
form.state.choices = [(row.id, row.name) for row in geoUtils.queryStateNamesWithCountryIdWithDefault(company.state_id, company.country_id)]
form.industry.choices = [(row.id, row.name) for row in mainUtils.queryIndustryNamesWithDefault(company.industry_id)]
form.legal_entity.choices = [(row.id, row.name) for row in companyUtils.queryLegalEntityNamesWithDefault(company.legal_entity_id)]
form.type.choices = [(row.id, row.name) for row in companyUtils.queryTypeNamesWithDefault(company.type_id)]
form.relation.choices = [(row.id, row.name) for row in companyUtils.queryRelationNamesWithDefault(company.relation_id)]
form.status.choices = [(row.id, row.name) for row in companyUtils.queryStatusNamesWithDefault(company.status_id)]
form.populate_choices(company)
if form.validate_on_submit():
if form.picture.data:
picture_file = mainUtils.save_picture(form.picture.data)
if form.image_file.data:
picture_file = mainUtils.save_picture(form.image_file.data)
company.image_file = picture_file
company.name = form.name.data
company.website = form.website.data
company.country_id = form.country.data
company.city_id = form.city.data
company.state_id = form.state.data
company.post_code = form.post_code.data
company.street = form.street.data
company.street_no = form.street_no.data
company.industry_id = form.industry.data
company.legal_entity_id = form.legal_entity.data
company.type_id = form.type.data
company.relation_id = form.relation.data
company.status_id = form.status.data
company.comment = form.comment.data
for item in form:
mainUtils.modelFill(company, item, ["image_file"])
dbUtils.dbCommit()
flash('Company Has been successfully updated', 'success')
return redirect(url_for('company.account', companyId=companyId))
elif request.method == 'GET':
form.name.data = company.name
form.website.data = company.website
form.country.data = company.country_id
form.city.data = company.city_id
form.state.data = company.state_id
form.post_code.data = company.post_code
form.street.data = company.street
form.street_no.data = company.street_no
form.legal_entity.data = company.legal_entity.name
form.type.data = company.type.name
form.comment.data = company.comment
for item in form:
item.data = mainUtils.formFill(item, company)
image_file = url_for('static', filename='pics/' + companyUtils.queryImageById(companyId))

@ -7,10 +7,10 @@
<div class="d-flex flex-column align-items-center text-center p-3 py-5">
<img class="rounded-circle mt-4 border-info" width="150px" src="{{ image_file }}">
<h2 class="account-heading" style="color: {{ theme.orange }};">{{ form.name.data }}</h2>
<h3 class="account-heading" style="color: {{ theme.orange }};">{{ form.legal_entity.data }}</h2>
<h3 class="account-heading" style="color: {{ theme.orange }};">{{ form.legal_entity_id.data }}</h2>
<h5 class="account-heading" style="color: {{ theme.light_blue }};">{{ form.website.data }}</h5>
<div class="p-3 py-5">
<h4 class="account-heading" style="color: {{ theme.yellow }};">{{ form.type.data }}</h4>
<h4 class="account-heading" style="color: {{ theme.yellow }};">{{ form.type_id.data }}</h4>
</div>
</div>
</div>

@ -37,7 +37,7 @@ def test():
@geography.route("/get_cities", methods=['GET', 'POST'])
def get_cities():
global country_id
country_id = request.args.get("country", type=int)
country_id = request.args.get("country_id", type=int)
print(f"/get_cities -> country_id: {country_id}")
cities = City.query.filter_by(country_id=country_id).all()
print(len(cities))

@ -8,6 +8,23 @@ from minibase.blueprints.main.models import Industries
import minibase.blueprints.database.utils as dbUtils
def formFill(item, table, to_ignore=[]):
if item.type not in ["SubmitField", "CSRFTokenField"]:
if item.name not in to_ignore:
attribute = getattr(table, item.name)
if hasattr(attribute, 'name'):
return getattr(attribute, 'name')
else:
return attribute
def modelFill(table, item, to_ignore=[]):
if item.type not in ["SubmitField", "CSRFTokenField"]:
print(item.type)
if item.name not in to_ignore:
setattr(table, item.name, item.data)
def save_picture(form_picture):
random_hex = secrets.token_hex(8)
_, f_ext = os.path.splitext(form_picture.filename)

Loading…
Cancel
Save