podstawowa obsługa bazy danych

This commit is contained in:
Mateusz779 2023-04-07 13:25:24 +02:00
parent c07f99a166
commit 699fe59388
3 changed files with 112 additions and 3 deletions

60
app.py
View File

@ -1,7 +1,61 @@
from flask import Flask, send_file
from flask import Flask, send_file, jsonify, request
import db
import os
from werkzeug.utils import secure_filename
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = "configs/squash"
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 512 #512MB
@app.route("api/addimage", methods=['POST'])
def add_image():
db.Connect()
name = None
try:
file = request.files['file']
if file is None or file == "":
return jsonify(message="nofile")
except Exception as e:
return jsonify(message="nofile")
try:
token = request.form['token']
if token is None or token == "":
return jsonify(message="notoken")
except:
if token is None:
return jsonify(message="notoken")
incorrect = True
while incorrect:
if db.GetVPNImage(token) is not None:
if name[-1:].isdigit():
name = name[:-1] + str(int(name[-1:])+1)
else:
name = name+"1"
else:
incorrect = False
filename = secure_filename(file.filename)
while os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
if filename[0].isdigit():
filename = str(int(filename[0])+1)+filename[1:]
else:
filename = "1"+filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
db.AddVPNImage(filename, token)
return jsonify(message="ok")
@app.route("/api/getvpn")
def hello_world():
return send_file("configs/squash/praktyki.squashfs")
def get_image():
try:
filename = db.GetVPNImage(request.args['token'])
except:
filename = "default.squashfs"
if filename is None or filename == "":
filename = "default.squashfs"
return send_file(os.path.join(app.config['UPLOAD_FOLDER'], filename))

5
config.py Normal file
View File

@ -0,0 +1,5 @@
database="praktyki"
host="localhost"
user="praktyki"
password="2a7driUITXFy73tO"
port="5432"

50
db.py Normal file
View File

@ -0,0 +1,50 @@
import psycopg2
import config
def Connect():
global cur, conn
try:
conn = psycopg2.connect(database=config.database,
host=config.host,
user=config.user,
password=config.password,
port=config.port)
except Exception as ex:
print(f"Error connecting to PostgreSQL: {e}")
cur = conn.cursor()
with conn.cursor() as cur:
cur.execute("""
CREATE TABLE IF NOT EXISTS vpn (
id SERIAL PRIMARY KEY,
image_name VARCHAR(255) NOT NULL,
token VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
def GetCur():
return conn.cursor()
def GetConn():
return conn
def AddVPNImage(name, token):
Connect()
with GetCur() as cur:
cur.execute("""
INSERT INTO vpn (image_name, token)
VALUES (%s, %s)
""",(name, token,))
conn.commit()
def GetVPNImage(token):
Connect()
with GetCur() as cur:
return cur.execute("""
SELECT image_name FROM vpn WHERE token = %s
""",(token,)).fetchone()