Skip to content
Snippets Groups Projects
Commit d4633ff8 authored by Oliwer Mattsson's avatar Oliwer Mattsson :headphones:
Browse files

Laddade upp uppdaterade python filer.

parent 1bc829ff
No related branches found
No related tags found
No related merge requests found
#!/.venv/bin/python #!/.venv/bin/python
# TODO
# Gör project_id dynamisk så att den uppdateras efter borttagning/addering av projekt.
# ---- IMPORTS ---- # # ---- IMPORTS ---- #
import os import os # Import os module for cls and executing commands through python
import json import json # Import json so we can handle our data.json file
import pprint import pprint # Pretty print for debugging
import re import re # Not used atm
import unicodedata import unicodedata # Not used atm
from operator import itemgetter from operator import itemgetter # Used for sorting our results after a specific option.
# ---- IMPORTS ---- # # ---- IMPORTS ---- #
# Opens a file and reads it so it's contents can be used as data for the program
def load(filename): def load(filename):
try: try:
# Opens file with R (read) with UTF 8 encoding as file
with open(filename, 'r', encoding='utf-8') as file: with open(filename, 'r', encoding='utf-8') as file:
data = json.load(file) data = json.load(file) # Assigns the file contents to data as json
file.close() file.close() # Close the file
return data return data
except: except:
return None return None
# WIP
def save(data): def save(data):
with open('data.json', 'w', encoding='utf-8') as file: with open('data.json', 'w', encoding='utf-8') as file:
json.dump(data, file, ensure_ascii=False, indent=4) json.dump(data, file, ensure_ascii=False, indent=4)
...@@ -37,93 +35,95 @@ def save(data): ...@@ -37,93 +35,95 @@ def save(data):
# Get project count # Get project count
def get_project_count(data): def get_project_count(data):
return len(data) return len(data) # Returns the len of the data list which is equivalent to the amount of projects
# Get project by ID # Get project by ID
def get_project(data, id): def get_project(data, id):
# Loops over a range with the length of the amount of projects present and gets a project if it matches the passed ID.
for n in range(0, get_project_count(data)): for n in range(0, get_project_count(data)):
if data[n]['project_id'] == id: if data[n]['project_id'] == id: # If the current projects ID corresponds to the ID we're looking for then...
return data[n] return data[n] # Return the project at that index
# Get all unique techniques from project # Get all unique techniques from project
def get_techniques(data): def get_techniques(data):
techniques = [] techniques = [] # A list which will store the techniques found
for project in data: for project in data: # For every project in our data
for tech in project['techniques_used']: for tech in project['techniques_used']: # For every technique in that project
if tech not in techniques: if tech not in techniques: # If it's not in the previously techniques, it's unique.
techniques.append(tech) techniques.append(tech) # Append it to the list.
techniques.sort() techniques.sort() # Sort it so it'll look nice.
return techniques return techniques
# Gets all unique techniques from all projects ! COULD USE SOME FILTERING ! # Gets all unique techniques from all projects. ( NOT USED? )
def get_technique_stats(data): def get_technique_stats(data):
technique_list = get_techniques(data) technique_list = get_techniques(data) # Get all the unique techniques so we know what techniques we can expect.
technique_stats = {} technique_stats = {} # Creates a dictionary which will contain the id as a key and the name as a value.
current_techniques = [] current_techniques = [] # A list which will contain the found techniques.
for technique in technique_list: for technique in technique_list: # For each unique technique we found with get_techniques()...
for project in data: for project in data: # For every project in data, as we need to look over them all for each technique.
if technique in project['techniques_used']: if technique in project['techniques_used']: # If the technique we're currently looking for is in the used techniques of the project we're iterating over.
current_techniques.append({'id': project['project_id'], 'name': project['project_name']}) current_techniques.append({'id': project['project_id'], 'name': project['project_name']}) # Create a new dict INSIDE the list with the project ID and project name.
technique_stats.update({technique: current_techniques.copy()}) technique_stats.update({technique: current_techniques.copy()}) # Updates the dictionary with the list WITH a dict inside.
current_techniques.clear() current_techniques.clear() # Clears the buffer so a new key value pair can be created.
return technique_stats return technique_stats # Return a dict with all techniques and the projects which uses them.
# Fetches and sorts projects matching criteria from the specified list. # Fetches and sorts projects matching criteria from the specified list.
def search(data, sort_by='start_date', sort_order='desc', techniques=None, search=None, search_fields=None): def search(data, sort_by='start_date', sort_order='desc', techniques=None, search=None, search_fields=None):
# If search str belongs to search and if so, make search lower case.
if isinstance(search, str): if isinstance(search, str):
search = search.lower() search = search.lower()
results = [] results = []
# get it # get it
for project in data: for project in data: # For each project in data
results.append(project) results.append(project) # Add all projects in data
# sort it # sort it
results = sorted(results, key=itemgetter(sort_by)) results = sorted(results, key=itemgetter(sort_by)) # Sorts our results based on a specific variable by using a lambda function with itemgetter.
# order it # order it
if sort_order == 'desc': if sort_order == 'desc': # If the sort order is set to desc, then reverse the list.
results.reverse() results.reverse()
# filter it (by techniques) # filter it (by techniques)
if techniques is not None: if techniques is not None: # If there are techniques which are going to be filtered by..
for technique in get_techniques(data): for technique in get_techniques(data): # For each unique technique..
for project in results: for project in results: # And for each project we've found so far..
if all(n in project['techniques_used'] for n in techniques): if all(n in project['techniques_used'] for n in techniques): # If all the techniques we're looking for are inside the projects technique_used field..
pass pass # Then do nothing..
else: else:
results.pop(results.index(project)) results.pop(results.index(project)) # Otherwise remove it from our results.
# search for it # search for it
if search is not None: if search is not None: # If the search field isn't set to None..
search_results = [] search_results = [] # Create a list for our search results..
for project in results: for project in results: # For every project we've found so far..
if search_fields is not None and search_fields != "" and search != "" and search_fields != ['None']: if search_fields is not None and search_fields != "" and search != "" and search_fields != ['None']: # If the searchf ield is not set to None AND search_fields is not empty AND search_fields is not an empty list..
for field in search_fields: for field in search_fields: # For each field in search fields..
substring = project[field] substring = project[field] # Save the current field in substring so we can do operations on it..
# Check type before calling lower() # Check types before calling lower()
if isinstance(substring, str): if isinstance(substring, str):
substring = substring.lower() substring = substring.lower() # Make case insensitive
if substring.find(search) != -1: if substring.find(search) != -1: # If found
search_results.append(project) search_results.append(project)
break break
elif isinstance(substring, int): elif isinstance(substring, int):
if str(substring).find(search) != -1: if str(substring).find(search) != -1:
search_results.append(project) search_results.append(project)
break break
elif isinstance(substring, list): elif isinstance(substring, list): # If it's a list..
for subsubstring in substring: for subsubstring in substring: # We'll need to make another substring so we can iterate over each index of the list instead of just for multiple lists.
if isinstance(subsubstring, str): if isinstance(subsubstring, str):
if subsubstring.lower().find(search) != -1: if subsubstring.lower().find(search) != -1:
search_results.append(project) search_results.append(project)
break break
...@@ -132,8 +132,8 @@ def search(data, sort_by='start_date', sort_order='desc', techniques=None, searc ...@@ -132,8 +132,8 @@ def search(data, sort_by='start_date', sort_order='desc', techniques=None, searc
search_results.append(project) search_results.append(project)
break break
elif search_fields == "": elif search_fields == "": # And if the search_fields is empty..
results.clear() results.clear() # Clear all results
break break
else: else:
...@@ -158,16 +158,19 @@ def search(data, sort_by='start_date', sort_order='desc', techniques=None, searc ...@@ -158,16 +158,19 @@ def search(data, sort_by='start_date', sort_order='desc', techniques=None, searc
search_results.append(project) search_results.append(project)
break break
results = search_results results = search_results # Make results into search_results as they should be the same
return results # Returns our results.
return results
# WIP
def cls(): def cls():
os.system('cls' if os.name == 'nt' else 'clear') os.system('cls' if os.name == 'nt' else 'clear')
pass pass
# WIP
def new_project(data): def new_project(data):
cls() cls()
...@@ -205,14 +208,14 @@ def new_project(data): ...@@ -205,14 +208,14 @@ def new_project(data):
pass pass
# WIP
def list_projects(data): def list_projects(data):
cls() cls()
for project in data: for project in data:
pprint.pp(project) pprint.pp(project)
print("\n") print("\n")
# WIP
def edit_project(data, id): def edit_project(data, id):
while True: while True:
if id > get_project_count(data) or id < 0: if id > get_project_count(data) or id < 0:
...@@ -232,11 +235,11 @@ def edit_project(data, id): ...@@ -232,11 +235,11 @@ def edit_project(data, id):
input("\nField to edit: ") input("\nField to edit: ")
# WIP
def delete_project(data): def delete_project(data):
pass pass
# WIP
def menu(data): def menu(data):
menu_items = ["Add new project", "List projects", "Edit existing project", "Delete project", "Quit"] menu_items = ["Add new project", "List projects", "Edit existing project", "Delete project", "Quit"]
menu_index = 0 menu_index = 0
......
...@@ -11,6 +11,8 @@ def index(): ...@@ -11,6 +11,8 @@ def index():
@app.route("/list", methods=['GET', 'POST']) @app.route("/list", methods=['GET', 'POST'])
def list(): def list():
# Gets POST data from forms
search_query = request.form.get('search', '') search_query = request.form.get('search', '')
sort_by = request.form.get('sort_by', 'start_date') sort_by = request.form.get('sort_by', 'start_date')
sort_order = request.form.get('sort_order', 'desc') sort_order = request.form.get('sort_order', 'desc')
...@@ -22,6 +24,7 @@ def list(): ...@@ -22,6 +24,7 @@ def list():
sort_by=sort_by, sort_by=sort_by,
sort_order=sort_order) sort_order=sort_order)
# Converts ID to int incase it's passed as string
@app.route("/project/<int:project_id>") @app.route("/project/<int:project_id>")
def project_details(project_id): def project_details(project_id):
project = get_project(load('data.json'), project_id) project = get_project(load('data.json'), project_id)
...@@ -33,8 +36,10 @@ def project_details(project_id): ...@@ -33,8 +36,10 @@ def project_details(project_id):
@app.route("/techniques", methods=['GET', 'POST']) @app.route("/techniques", methods=['GET', 'POST'])
def techniques(): def techniques():
# Gets all unique techniques in our projects using get_technique_stats function.
techniques = get_technique_stats(load('data.json')) techniques = get_technique_stats(load('data.json'))
# Gets POST data from forms
search_query = request.form.get('search', '') search_query = request.form.get('search', '')
sort_by = request.form.get('sort_by', 'start_date') sort_by = request.form.get('sort_by', 'start_date')
sort_order = request.form.get('sort_order', 'desc') sort_order = request.form.get('sort_order', 'desc')
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment