Primo Commit

This commit is contained in:
Massimiliano Saguto 2024-07-16 11:26:11 +02:00
commit 511df8b006
12 changed files with 273 additions and 0 deletions

4
.gitignore vendored Normal file

@ -0,0 +1,4 @@
env/
src/__pycache__/
src/tools/__pycache__/
src/models/__pycache__/

24
README.md Normal file

@ -0,0 +1,24 @@
### PYTHON 2
### sudo apt-get install python-dev libpq-dev
### virtualenv -p python env
### python -m pip install --upgrade pip
### pip install -r src/requirements.txt
### pip install 'SQLAlchemy < 1.4.0'
### PYTHON 3
### sudo apt-get install python3-pip python3-dev python3-venv python3-virtualenv libpq-dev
### python3 -m venv env
### python3 -m pip install --upgrade pip
### pip3 install wheel
### pip3 install -r src/requirements.txt
### pip3 install 'SQLAlchemy < 1.4.0'
### VENV
### source env/bin/activate (LINUX/MAC)
### env\Scripts\activate.bat (WINDOWS)
### deactivate
### cd src
### python3
### from models.BotInfos import db
### db.create_all()

12
src/Config.py Normal file

@ -0,0 +1,12 @@
import os
from flask import Flask, request, Response, jsonify
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
#app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://qvpnplqo:qD18ZQamANmgkKGHAAUgzDRQqKXuAajC@tai.db.elephantsql.com/qvpnplqo'
app.config['SQLALCHEMY_DATABASE_URI'] = 'postgres://postgres:postgres@localhost:5432/postgres?options=-csearch_path%3Ddev'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
basedir = os.path.abspath(os.path.dirname(__file__))

90
src/Main.py Normal file

@ -0,0 +1,90 @@
import logging
from tools.Postgresql import Postgresql
from models.RipDefs import *
from models.BotInfos import *
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
@app.route('/', methods=['GET', 'POST', 'PUT'])
def hello():
return 'Hello, World!'
@app.route('/<name>', methods=['GET'])
def hello_name(name):
return "Hello {}!".format(name)
@app.route('/bots', methods=['GET'])
def get_bots():
return jsonify({'Bots': BotInfos.get_all_bots()})
@app.route('/bots/<int:id>', methods=['GET'])
def get_bot_by_id(id):
return_value = BotInfos.get_bot(id)
return jsonify(return_value)
@app.route('/bots', methods=['POST'])
def add_bot():
request_data = request.get_json()
BotInfos.add_bot(
request_data["bot_name"],
request_data["bot_token"],
request_data["owner_name"],
request_data["owner_phone_number"]
)
response = Response("Bot aggiunto", 200, mimetype='application/json')
return response
@app.route('/rips', methods=['GET'])
def get_rips():
return jsonify({'Rips': RipDefs.get_all_rips()})
@app.route('/rips/<int:id>', methods=['GET'])
def get_rip_by_id(id):
return_value = RipDefs.get_rip(id)
return jsonify(return_value)
def main():
try:
connection = None
try:
connectionResponse = Postgresql.connect()
connection = connectionResponse["connection"]
error = connectionResponse["error"]
if error == None:
logger.debug("CONNESSO!!!")
cursor = connection.cursor()
sql = "SELECT id, bot_name, bot_token FROM botinfos where bot_name = 'SettoreSviluppoDevBot'"
cursor.execute(sql)
result = cursor.fetchone()
logger.debug(result)
else:
logger.error(error)
finally:
if connection != None and error == None:
if cursor != None:
cursor.close()
connection.commit()
connection.close()
except Exception as e:
logger.error("EXCEPTION!!! -> ERRORE: '" + str(e) + "'")
if __name__ == '__main__':
main()
app.run(debug = True, host = "0.0.0.0", port = 5000)

BIN
src/database.db Normal file

Binary file not shown.

48
src/models/BotInfos.py Normal file

@ -0,0 +1,48 @@
from Config import *
import json
db = SQLAlchemy(app)
class BotInfos(db.Model):
__tablename__ = 'botinfos'
id = db.Column(db.Integer, primary_key=True)
bot_name = db.Column(db.String(255), nullable=False)
bot_token = db.Column(db.String(255), nullable=False)
owner_name = db.Column(db.String(255), nullable=False)
owner_phone_number = db.Column(db.String(255), nullable=False)
def json(self):
return {
'id': self.id,
'bot_name': self.bot_name,
'bot_token': self.bot_token,
'owner_name': self.owner_name,
'owner_phone_number': self.owner_phone_number
}
def add_bot(_bot_name, _bot_token, _owner_name, _owner_phone_number):
new_bot = BotInfos(bot_name=_bot_name, bot_token=_bot_token, owner_name=_owner_name, owner_phone_number=_owner_phone_number)
db.session.add(new_bot)
db.session.commit()
def get_all_bots():
return [BotInfos.json(botinfos) for botinfos in BotInfos.query.all()]
def get_bot(_id):
return [BotInfos.json(BotInfos.query.filter_by(id=_id).first())]
# BotInfos.json() coverts our output to json
# the filter_by method filters the query by the id
# the .first() method displays the first value
def update_bot(_id, _bot_name, _bot_token, _owner_name, _owner_phone_number):
bot_to_update = BotInfos.query.filter_by(id=_id).first()
bot_to_update.bot_name = _bot_name
bot_to_update.bot_token = _bot_token
bot_to_update.owner_name = _owner_name
bot_to_update.owner_phone_number = _owner_phone_number
db.session.commit()
def delete_bot(_id):
BotInfos.query.filter_by(id=_id).delete()
db.session.commit()

28
src/models/RipDefs.py Normal file

@ -0,0 +1,28 @@
from Config import *
import json
db = SQLAlchemy(app)
class RipDefs(db.Model):
__tablename__ = 'rip_def'
gid = db.Column(db.Integer, primary_key=True, nullable=False)
cod_rip = db.Column(db.Integer)
den_rip = db.Column(db.String(50))
shape_leng = db.Column(db.Integer)
shape_area = db.Column(db.Integer)
def json(self):
return {
'gid': self.gid,
'cod_rip': self.cod_rip,
'den_rip': self.den_rip,
'shape_leng': self.shape_leng,
'shape_area': self.shape_area
}
def get_all_rips():
return [RipDefs.json(ripdefs) for ripdefs in RipDefs.query.all()]
def get_rip(_id):
return [RipDefs.json(RipDefs.query.filter_by(id=_id).first())]

0
src/models/__init.__py Normal file

9
src/requirements.txt Normal file

@ -0,0 +1,9 @@
python-dateutil==2.8.1
PyJWT==1.7.1
requests==2.23.0
requests-toolbelt==0.9.1
PyMySQL==0.10.1
psycopg2-binary==2.8.6
SQLAlchemy<1.4.0
flask-sqlalchemy==2.4.4
GeoAlchemy2==0.9.4

28
src/tools/Mysql.py Normal file

@ -0,0 +1,28 @@
import json
import logging
import pymysql.cursors
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
class Mysql():
def connect():
response = {
"connection": None,
"error": None
}
try:
connection = pymysql.connect(host='54.93.78.252',
user='root',
password='Massi001',
db='peperonciniindoorbot',
charset='utf8',
cursorclass=pymysql.cursors.DictCursor)
response["connection"] = connection
except Exception as e:
response["error"] = str(e)
logger.error("EXCEPTION!!! -> ERRORE: '" + str(e) + "'")
return response

30
src/tools/Postgresql.py Normal file

@ -0,0 +1,30 @@
import json
import logging
import psycopg2
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__name__)
class Postgresql():
def connect():
response = {
"connection": None,
"error": None
}
try:
host = "tai.db.elephantsql.com"
dbname = "qvpnplqo"
user = "qvpnplqo"
password = "qD18ZQamANmgkKGHAAUgzDRQqKXuAajC"
sslmode = "require"
conn_string = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(host, user, dbname, password, sslmode)
response["connection"] = psycopg2.connect(conn_string)
except Exception as e:
response["error"] = str(e)
logger.error("EXCEPTION!!! -> ERRORE: '" + str(e) + "'")
return response

0
src/tools/__init.__py Normal file