#python #python-3.x #flask #input #python-requests
#python #python-3.x #flask #input #python-requests
Вопрос:
У меня проблема с получением файла из входного html и передачей его в качестве входного в алгоритме python для отображения графиков, я использую flask, и алгоритмы, которые я хочу запустить, находятся в algo_kruskal_final и algo_prim_final, это мой каталог под названием интерфейс.
Это мое app.py:
from flask import Flask, render_template, request, url_for, redirect from flask_bootstrap import Bootstrap import os import datetime import time from algo_prim_final import * from algo_kruskal_final import * from werkzeug.utils import secure_filename import networkx as nx import matplotlib.pyplot as plt # files = '/files' # ALLOWED_EXTENSIONS = {'txt'} app = Flask (__name__) @app.route('/', methods=['GET']) def hello_world(): return render_template('index.html') @app.route('/',methods=['POST']) def reskruskal(): textfile = request.form.get("textfile") textfile= request.files['textfile'] textfile_path="./files/" textfile.filename textfile.save(textfile_path) return render_template('index.html', textfile=textfile) def submit(textfile): if request.method == "POST": if request.form.get("run_krus"): algo_kruskal_final.run() elif request.form.get("run_prim"): algo_prim_final.run() # return ''' #lt;!doctype htmlgt; #lt;titlegt;Upload new Filelt;/titlegt; #lt;h1gt;Upload new Filelt;/h1gt; #lt;form method=post enctype=multipart/form-datagt; #lt;input type=file name=textfilegt; #lt;input type=submit value=Uploadgt; #lt;/formgt; #''' bootstrap = Bootstrap(app) if __name__ =='__main__': app.run(debug=True)
Это мое algo_kruskal_final.py:
import networkx as nx import matplotlib.pyplot as plt from app import textfile_path,file_content,textfile with open(textfile_path, 'r') as f: file_content = f.read() g=nx.read_weighted_edgelist(file_content,create_using=nx.Graph(), delimiter=' ', nodetype=int) print(nx.info(g)) print (g.number_of_nodes()) nx.draw(g, with_labels=True) plt.title('AVANT KRUSKAL') plt.show() V= g.number_of_nodes() a_file = open(file_content, "r") list_of_tuples = [] for line in a_file: stripped_line = line.strip() line_list = tuple (stripped_line.split()) list_of_tuples.append(line_list) a_file.close() print(list_of_tuples) def kruskal(edges: list) -gt; list: """ kruskal - fonction pour déterminer le plus cout chemin :paramétre: List des noeuds sous forme d'un tuple(a, b, valeur de l'arc) :résultat: List des noeuds /arcs qui représente le plus court chemin. """ # Sorting input edges by weight edges = sorted(edges, key=lambda item: item[2]) # Adding first edge (with smallest weight) to result list and deleting it from input edges. result = [edges.pop(0)] # Adding to array first set of expanded points. array = [{result[0][0], result[0][1]}] # For each edge in sorted list (without deleted first) for edge in edges: # Looking for start point occurrences in expanded points sets and trying to get set index. start_connection = next(iter([i for i in range(len(array)) if edge[0] in array[i]]), None) # Looking for end point occurrences in expanded points sets and trying to get set index. end_connection = next(iter([i for i in range(len(array)) if edge[1] in array[i]]), None) # If edge makes cycle - skip it. if start_connection is not None and start_connection == end_connection: continue # Adding edge to result list. result.append(edge) # If edge first point found in expanded points set - add second edge point. if start_connection is not None: array[start_connection].add(edge[1]) # If edge second point found in expanded points set - add first edge point. if end_connection is not None: array[end_connection].add(edge[0]) # If edge is not connected with any chains - add new set of expanded points. (new chain) if start_connection is None and end_connection is None: array.append({edge[0], edge[1]}) # If edge connects two chains - merge these chains. (union from two expanded points sets) if start_connection is not None and end_connection is not None: array.append(array[start_connection].union(array[end_connection])) array = [array[i] for i in range(len(array)) if i != start_connection and i != end_connection] return result EDGES = list_of_tuples print(EDGES) print(kruskal(EDGES)) G_kruskal = nx.Graph() G_kruskal.add_weighted_edges_from(kruskal(EDGES)) nx.draw(G_kruskal, with_labels=True) plt.title('APRES KRUSKAL') plt.show()
And this is my algo_prim_final.py:
import networkx as nx import matplotlib.pyplot as plt from app import textfile_path,file_content,textfile with open(textfile_path, 'r') as f: file_content = f.read() G=nx.read_weighted_edgelist('file_content',create_using=nx.Graph(), delimiter=' ', nodetype=int) nx.draw(G, with_labels=True) plt.title('AVANT PRIM') plt.show() noeuds= G.number_of_nodes() print(noeuds) listofedges = [[int(v) for v in line.split()] for line in open(file_content)] print(listofedges) def createAdjMatrix(V, G): adjMatrix = [] #create N x N matrix filled with 0 edge weights between all vertices for i in range(0, V): adjMatrix.append([]) for j in range(0, V): adjMatrix[i].append(0) #populate adjacency matrix with correct edge weights for i in range(0, len(G)): adjMatrix[G[i][0]][G[i][1]] = G[i][2] adjMatrix[G[i][1]][G[i][0]] = G[i][2] return adjMatrix def prims(V, G): # create adj matrix from graph adjMatrix = createAdjMatrix(V, G) #arbitrarily choose initial vertex from graph vertex = 0 #initialize empty edges array and empty MST MST = [] edges = [] visited = [] minEdge = [None,None,float('inf')] #run prims algorithm until we create an MST #that contains every vertex from the graph while len(MST) != V-1: #mark this vertex as visited visited.append(vertex) #add each edge to list of potential edges for r in range(0, V): if adjMatrix[vertex][r] != 0: edges.append([vertex,r,adjMatrix[vertex][r]]) #find edge with the smallest weight to a vertex #that has not yet been visited for e in range(0, len(edges)): if edges[e][2] lt; minEdge[2] and edges[e][1] not in visited: minEdge = edges[e] #remove min weight edge from list of edges edges.remove(minEdge) #push min edge to MST MST.append(minEdge) #start at new vertex and reset min edge vertex = minEdge[1] minEdge = [None,None,float('inf')] return MST #graph vertices are actually represented as numbers #like so: 0, 1, 2, ... V-1 #a, b, c, d, e, f = 0, 1, 2, 3, 4, 5 #graph edges with weights #diagram of graph is shown above graph = listofedges #pass the # of vertices and the graph to run prims algorithm print(prims(noeuds, graph)) g_prim=nx.Graph() g_prim.add_weighted_edges_from((prims(noeuds, graph))) nx.draw(g_prim, with_labels=True) plt.title('APRES PRIM') plt.show()
And finally index.html:
lt;h1 class="text-center"gt;Algorithme KRUSKAL/PRIM lt;/h1gt; lt;form class="p-3 text-center" action='/', method="post" enctype="multipart/form-data"gt; lt;input class="form-control col-xs-4" type="file" name="textfile" accept=".txt"gt; lt;br/gt;lt;br/gt;lt;br/gt; lt;divgt; lt;div class="d-grid gap-2 d-md-block"gt; lt;button class="btn btn-primary" type="submit" name="run_Krus"gt;Kruskallt;/buttongt; lt;button class="btn btn-primary" type="submit" name="run_prim"gt;Primlt;/buttongt; lt;/divgt; lt;/divgt; lt;/formgt;
So the idea is passing a file from an html input and run it in a webpage, show the plots as well.
Thank you.