jagata

fucking unilab project

Aug 5th, 2021
735
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import sqlite3 as sql
  2. from os import path
  3. from flask import Flask, request, jsonify
  4. app = Flask(__name__)
  5.  
  6. dbname = "students_marks.db"
  7. if not path.isfile(dbname):
  8.     connect = sql.connect(dbname)
  9.     cur = connect.cursor()
  10.     cur.execute("""CREATE TABLE IF NOT EXISTS students_marks (
  11.  
  12.                                    id INTEGER PRIMARY KEY AUTOINCREMENT,
  13.                                    first_name TEXT,
  14.                                    last_name TEXT,
  15.                                    subject TEXT,
  16.                                    point FLOAT DEFAULT 0
  17.                                      )""")
  18.     connect.close()
  19.     print("Database successfully created")
  20. else:
  21.     print("Database allready exists")
  22.  
  23.  
  24. class options:
  25.     def __init__(self,dbfile):
  26.         self.connection = sql.connect(dbfile)
  27.     def escape(self,d_string):
  28.         d_string = d_string.replace("'","`")
  29.         return d_string.strip()
  30.  
  31.     def load_data(self,id):
  32.         if id != None:
  33.             cur = self.connection.cursor()
  34.             cur.execute(f"SELECT * from students_marks where id={id}")
  35.             data = cur.fetchone()
  36.  
  37.             self.connection.close()
  38.             return data
  39.         else:
  40.             cur = self.connection.cursor()
  41.             cur.execute(f"SELECT * from students_marks order by id desc")
  42.             data = cur.fetchall()
  43.             self.connection.close()
  44.             return data
  45.  
  46.     def add_new(self,first_name,last_name,subject,point):
  47.         cur = self.connection.cursor()
  48.         add = cur.execute(f"INSERT INTO students_marks (first_name,last_name,subject,point) VALUES ('{self.escape(first_name)}','{self.escape(last_name)}','{self.escape(subject)}','{point}')")
  49.         self.connection.commit()
  50.         self.connection.close()
  51.         return "successfully added"
  52.     def delete(self,id):
  53.         cur = self.connection.cursor()
  54.         delete = cur.execute(f"DELETE FROM students_marks WHERE id={id}")
  55.         self.connection.commit()
  56.         self.connection.close()
  57.         if delete.rowcount == 1:
  58.             return f"successfully deleted"
  59.         else:
  60.             return f"There is no any record where id = {id}"
  61.  
  62.     def update(self,info,update_by):
  63.         cur = self.connection.cursor()
  64.  
  65.         if update_by != "insert":
  66.             update = {}
  67.             for key,value in info.items():
  68.                 if key == "id" or update_by == key:
  69.                     continue
  70.                 if value != None:
  71.                     if len(value) == 0:
  72.                         return f"{key} must be filled"
  73.                     update[key]=value
  74.             if len(update) == 0:
  75.                 return "You must specify at least one update parameter"
  76.             else:
  77.                 if info['point'] != None:
  78.                     try:
  79.                         point = float(info['point'])
  80.                     except ValueError:
  81.                         return "Point must be float"
  82.                     except:
  83.                         return "Something went wrong"
  84.                 up = ','.join([key+"='"+str(self.escape(value))+"'" for key,value in update.items()])
  85.                 #print(f"UPDATE students_marks SET {up} WHERE {update_by}='{self.escape(str(info[update_by]))}'")
  86.                 update = cur.execute(f"UPDATE students_marks SET {up} WHERE {update_by}='{self.escape(str(info[update_by]))}'")
  87.  
  88.                 self.connection.commit()
  89.                 self.connection.close()
  90.                 if update.rowcount > 0:
  91.                     return "successfully updated"
  92.                 else:
  93.                     return f"There is no any record where {update_by} = {self.escape(str(info[update_by]))}"
  94.         else:
  95.             res = self.add_new(info['first_name'],info['last_name'],info['subject'],info['point'])
  96.             return res
  97.  
  98.  
  99.  
  100.  
  101.  
  102. @app.route("/<int:id>", methods=['GET'])
  103. def load_data(id):
  104.     for_load = options(dbname)
  105.     resp = for_load.load_data(id)
  106.     if resp == None:
  107.         return "There is no any record in database"
  108.     else:
  109.         result = {}
  110.         result[0] = {"id":resp[0],"first_name":resp[1],"last_name":resp[2],"subject":resp[3],"point":resp[4]}
  111.         return jsonify(result)
  112. @app.route("/", methods=['GET'])
  113. def load_full():
  114.     for_load = options(dbname)
  115.     resp = for_load.load_data(None)
  116.     if resp == None:
  117.         return "There is no any record in database"
  118.     else:
  119.         result = {}
  120.         i=0
  121.         for each in resp:
  122.             result[i] = {"id":each[0],"first_name":each[1],"last_name":each[2],"subject":each[3],"point":each[4]}
  123.             i+=1
  124.         return jsonify(result)
  125.  
  126. @app.route("/add", methods=['POST'])
  127. def add_row():
  128.     first_name = request.args.get("first_name", None, type=str)
  129.     last_name = request.args.get("last_name", None, type=str)
  130.     subject = request.args.get("subject", None, type=str)
  131.     point = request.args.get("point", None)
  132.     if first_name == None or last_name == None or subject == None or point == None:
  133.         return f"All fields must be filled"
  134.     elif len(first_name.strip())==0:
  135.         return f"First name must be filled"
  136.     elif len(last_name.strip())==0:
  137.         return f"Last name must be filled"
  138.     elif len(subject.strip())==0:
  139.         return f"Subject must be filled"
  140.     elif len(str(point).strip())==0:
  141.         return f"Point must be filled"
  142.     else:
  143.         try:
  144.             point = float(point)
  145.         except ValueError:
  146.             return "Point must be float"
  147.         except:
  148.             return "Something went wrong"
  149.         for_add = options(dbname)
  150.         added = for_add.add_new(first_name,last_name,subject,point)
  151.         return f"{added}"
  152. @app.route("/delete", methods=['DELETE'])
  153. def delete():
  154.     for_delete = options(dbname)
  155.     id = request.args.get("id", None)
  156.     if id == None:
  157.         return "Add id parameter"
  158.     try:
  159.         id = int(id)
  160.     except ValueError:
  161.         return "id must be integer"
  162.     except:
  163.         return "Something went wrong"
  164.     resp = for_delete.delete(id)
  165.     return resp
  166.  
  167.  
  168. @app.route("/update", methods=['PUT'])
  169. def update():
  170.     for_delete = options(dbname)
  171.  
  172.     first_name = request.args.get("first_name", None, type=str)
  173.     last_name = request.args.get("last_name", None, type=str)
  174.     subject = request.args.get("subject", None, type=str)
  175.     point = request.args.get("point", None)
  176.     id = request.args.get("id", None)
  177.     update_by = request.args.get("update_by", None)
  178.     if update_by == None:
  179.         return f"update_by must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  180.     elif update_by == "first_name" and first_name == None:
  181.         return f"{update_by} must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  182.     elif update_by == "last_name" and last_name == None:
  183.         return f"{update_by} must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  184.     elif update_by == "subject" and subject == None:
  185.         return f"{update_by} must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  186.     elif update_by == "point" and point == None:
  187.         return f"{update_by} must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  188.     elif update_by == "id" and id == None:
  189.         return f"{update_by} must be filled\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  190.     elif update_by == "insert":
  191.         if first_name == None or last_name == None or subject == None or point == None:
  192.             return f"first_name, last_name, subject, point must be filled!!!\n\nYou must fill update_by parameter and one of them (first_name, last_name, subject, point) in order to update row. if you want to insert new row fill everything. \n Parameters:\nfirst_name string,\nlast_name string,\nsubject string,\npoint float,\nid integer,\nupdate_by can be set first_name, last_name, subject, point, id, insert\n"
  193.         elif len(first_name.strip())==0:
  194.             return f"First name must be filled"
  195.         elif len(last_name.strip())==0:
  196.             return f"Last name must be filled"
  197.         elif len(subject.strip())==0:
  198.             return f"Subject must be filled"
  199.         elif len(str(point).strip())==0:
  200.             return f"Point must be filled"
  201.         else:
  202.             try:
  203.                 point = float(point)
  204.             except ValueError:
  205.                 return "Point must be float"
  206.             except:
  207.                 return "Something went wrong"
  208.     if update_by not in ['first_name', 'last_name', 'subject', 'point', 'id','insert']:
  209.         return "Incorrect update_by values"
  210.     if update_by == "id":
  211.          try:
  212.              id = int(id)
  213.          except ValueError:
  214.              return "id must be integer"
  215.          except:
  216.              return "Something went wrong"
  217.  
  218.     resp = for_delete.update({"first_name":first_name,"last_name":last_name,"subject":subject,"point":point,"id":id},update_by)
  219.     return resp
  220.  
  221.  
  222. if __name__ == "__main__":
  223.     app.run(host="127.0.0.1", port="80",debug=True)
  224.  
RAW Paste Data