Почему моя веб-страница создается вместе с обновлением flask каждый раз, когда я нажимаю кнопку отправки - PullRequest
0 голосов
/ 02 августа 2020

Я создаю программу flask, которая генерирует определенное количество паролей в зависимости от требований пользователя. Пользователь получает свободу редактирования пароля. Исходный код указан ниже.

Password_creator.py

from random import *
from itertools import *
import string
class password_generator():  
   def __init__(self,final_output,special_nproduction,final_specp): #creating the local variables
       self.final_output = final_output
       self.special_nproduction = special_nproduction
       self.final_specp = final_specp
      
      
   def alpha_rand_func(self): #for randomly selecting alphabets
       alpha = string.ascii_letters
       for i in range(4):
           self.final_output += choice(alpha)
        
   def symbol_rand_func(self): #for randomly selecting symbols
      symbol = string.punctuation
      for i in range(3):
         self.special_nproduction += choice(symbol)
             
   def int_rand_func(self): #for randomly selecting integers
      integer = string.digits
      for i in range(2):
         self.special_nproduction += choice(integer)
        
   def special_number_production(self): #for concatenating the integers and symbols
          self.special_nproduction = list(self.special_nproduction)
          init_perm = list(permutations((self.special_nproduction),5))
          selected_comb_init_list = choice(init_perm) #selecting a permutation of integers and symbols randomly
          mod_selected_comb_init = "" #for storing the permutation in the form of a variable
          for i in selected_comb_init_list: #iterating through the selected_comb_init_list
             mod_selected_comb_init += i 
          self.final_output += mod_selected_comb_init  # adding the integer-symbol combination to final output
   def final_output_production(self): #for concatenating all the characters, selecting a combination of it randommly and returning it as output
           return self.final_output #returns the final output
####################################          

####################################

exec_prog.py

from Password_creator import *
from flask import Flask,render_template,request,redirect,url_for
from table import Table
from flask_modus import Modus
app = Flask(__name__,template_folder='template')
modus= Modus(app)
@app.route("/")
def data_reveal(): # for user input for suggestions
    return render_template('input.html')

@app.route('/data-extract') # for extracting the user input
def data_extract():
    global sug
    sug = int(request.args.get('sug')) # to get the user input
    return redirect('/generate') # redirecting to generate
@app.route('/generate') # for generating the passwords
def generate():
    global final_g
    global data_x
    global password
    final_g = [] # for the passwords
    password = []
    for i in range(sug):
     v =  password_generator("","","") #for calling the class
     alpha_g = v.alpha_rand_func()    # line 25- 30; please refer the Password_creator.py file                 
     sym_g = v.symbol_rand_func()
     int_g = v.int_rand_func()
     spec_g = v.special_number_production()     
     final = v.final_output 
     final_g.append(v.final_output)
     passwd_obj = Table(v.final_output,'nil') # for storing them in a class 
     password.append(passwd_obj) # for storing them in a list
    print(final_g) 
    
    return render_template('output_disp.html',final_lst = password) # rendering the output_disp.html

###############
@app.route('/generate/<int:id>',methods = ["GET","PATCH","POST"]) # for modifying the function
def show(id):
     found  =  next(entry for entry in password if entry.id == id) # for finding the entry with the required entry
     if request.method  == b"PATCH": # for dealing with PATCH 
        found.passwd = request.form['edit_passwd']
        return redirect('/generate')
     return render_template('modify.html',found_entry = found)
    

@app.route('/generate/<int:id>/edit',methods = ["GET","PATCH","POST"]) # for showing the function
def modify(id):
    found  =  next(entry for entry in password if entry.id == id)
    return render_template('modify.html',found_entry = found)
###############

изменить. html

{% extends 'str_main.html' %}
{% block content %}
<div id  = "modify-div">
<form id = "edit" action = "{{url_for('show',id  = found_entry.id)}}?_method=PATCH" method ="POST">
   <input type = "text" value = "{{found_entry.passwd}}" name = "edit_passwd">
   <input type ="submit" value = "save change" >
</form>
</div>
{% endblock %}

output_disp. html

{% extends 'str_main.html'%}
{% block content%}
<div id  =  "options">
  <div id  = "btn-output-1"><h6>Upload file</h6></div>
  <div id  = "btn-output-2"><h6>Main page</h6></div>
  <div id  = "btn-output-3"><h6>Save</h6></div> 
</div>
<div id = "output-head">
  <h1>Here are the suggestions</h1>
</div>
<div id  = "output-div">  
  <form id = "output-data" method = "POST">   
    <table>
         <tr>
           <th>Password</th>
           <th>Description</th>
         </tr>
         
         {% for i in final_lst %}
        <tr>    
           <td> <a href ="#">{{ i.passwd }}</a></td> 
           <td>{{ i.desc }}</td>
        </tr>     
         {% endfor %}
    </table>
    <input type = "text" value = "fileName" name = "fileName">
    <button type ="button" value= "saving file">Saving fhile</button>
  </form>
</div>   

{% endblock %}

table.py

class Table(): #class for storing the passwords with their description
    count  = 1
    def __init__(self,passwd,desc):
        self.passwd = passwd
        self.desc = desc
        self.id = Table.count
        Table.count += 1

Вот URL-адрес репозитория github https://github.com/OCTRACORE/cs_Project

Проблема в том, что всякий раз, когда я go перехожу к маршруту /generate/<int:id>/edit и пытаюсь изменить пароль, Я не вижу изменений в output_disp.html. Вместо этого страница обновляется, и я вижу новый набор предложений. Итак, что я могу сделать, чтобы решить эту проблему.

1 Ответ

0 голосов
/ 02 августа 2020

Хорошо, поэтому, просмотрев ваш код, я думаю, что понял вашу проблему.

Однако я хочу сказать, что в вашем коде много плохих практик. Один из самых больших - использование глобальных переменных в веб-приложении. Вы никогда не должны этого делать. Если вы планируете запускать несколько экземпляров этого приложения для обработки большего количества запросов, тогда другие экземпляры не будут иметь доступа к другим глобальным экземплярам, ​​поэтому у вас будет много ошибок, которые будет сложно отследить.

В любом случае проблема I см. в вашей функции generate.

Когда вы отправляете изменение пароля, он сохраняется. Но это сохранение полностью уничтожено, потому что в вашей функции generate вы не проверяете предыдущие пароли, у вас также нет возможности узнать, изменилось ли что-то или вы действительно хотите сгенерировать новый набор паролей.

Мой совет

  • Изучите правильную настройку и структуру веб-приложения.

  • Никогда не используйте глобальные переменные в веб-приложении. Из-за этого будет получено слишком много ошибок, и их будет сложно найти.

  • Похоже, ваше приложение будет обычным веб-приложением без javascript или ajax, поэтому не используйте PATCH или DELETE для методов формы. Используйте GET и POST и используйте разные URL-адреса, чтобы решить, как обрабатывать эти запросы.

Если для flask нет хорошего руководства по настройке конечных точек / URL-адресов для вашего приложения , затем посмотрите настройки для Django проектов. Flask имитирует Django разными способами обработки конечных точек / URL-адресов.

...