如何解决如何从具有字节格式数据的文件中读取字符串?
我正在从Flask开发CRUD应用程序。它根据用户输入随机生成许多密码。用户还可以将输入保存在CSV文件中,然后在终端上打印输出。
这是源代码
exec_prog.py (用于创建Web界面)
from Password_creator import *
from flask import Flask,render_template,request,redirect,url_for
from csv import *
from table import Table
from flask_modus import Modus
from werkzeug import secure_filename
from cryptography.fernet import Fernet
app = Flask(__name__,template_folder='template')
modus= Modus(app)
@app.route("/")
def data_input(): # 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/new') # redirecting to generate
@app.route('/generate/new') # 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
return redirect('/generate/show-output')
@app.route('/generate/show-output',methods = ["GET","POST"])
def show_output():
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 id
if request.method == b"PATCH": # for dealing with PATCH
found.passwd = request.form['edit_passwd']
found.desc = request.form['description']
return redirect('/generate/show-output')
return render_template('modify.html',found_entry = found)
@app.route('/generate/file-manip-disp') # for displaying the uploading and downloadng options for password
def disp_manip_menu():
return render_template('file-manip.html')
@app.route('/generate/file-manip',"POST"]) # for uploading the passwords
def save_file():
pass_output_lst = [] #for passwords
desc_output_lst = [] #for descriptions of the password
encrypted_pass_output_lst = [] #storing passwords after encryption
encrypted_desc_output_lst = [] #storing descriptions of passwords after encryption
if request.method == "POST": # checking if the request method is POST
pass_file = request.files['fileName'] #requesting the name of the password saving file
pass_file_Name = secure_filename(pass_file.filename) #storing the name of the password saving file
key = Fernet.generate_key() # generating a key
key_init = Fernet(key) # storing the key for encrypting purpose
key_file = request.files['keyfile'] # requesting the key saving file
key_file_name = secure_filename(key_file.filename) #storing the name of the key saving file
for i in password:
encrypted_pass_output_lst.append(key_init.encrypt(bytes(i.passwd,encoding = "utf-8"))) #line 79 -80: storing the passwords and descriptions
encrypted_desc_output_lst.append(key_init.encrypt(bytes(i.desc,encoding = "utf-8"))) #by converting them into bytes and then encrypting them
with open(pass_file_Name,"w") as k: #for writing the password and description in the required file
writer_param = writer(k,delimiter=":",quoting = QUOTE_NONE,quotechar=" ") #csv writer
for i in range(sug):
writer_param.writerow([encrypted_pass_output_lst[i],encrypted_pass_output_lst[i]]) # writing the contents of the list
with open(key_file_name,"wb") as k: # for writing the key in the required file
k.write(key)
return render_template("file-manip.html",message = "file saved succesfully")
@app.route('/generate/file-manip-upload',"POST"])
def upload_file(): #for uploading the file
encrypted_pass_output_lst = []
encrypted_desc_output_lst = []
Upload_key = "" #for storing the key
if request.method == "POST":
Uploadfile= request.files['Uploadfile'] #requesting the name of the required file
Uploadfile_req = secure_filename(Uploadfile.filename) #storing the name of the password saving file
Uploadkeyfile = request.files['Uploadkeyfile'] #requesting the name of the key storing file
Uploadkeyfile_req = secure_filename(Uploadkeyfile.filename) #storing the name of the key storing file
with open(Uploadkeyfile_req,"rb") as k: #for reading the data of the key storing file and storing it in Upload_key
Upload_key = k.read()
Upload_key_init = Fernet(Upload_key) # for storing the key for decrypting purpose
with open(Uploadfile_req,"rb") as k: # opening the password-storing file
reader_param = reader(k,quoting=QUOTE_NONE,quotechar=" ") #csv reader
for arr in reader_param:
encrypted_pass_output_lst.append( Upload_key_init.decrypt(arr[0]) ) #line 105-106: storing the passwords and descriptions in the
encrypted_desc_output_lst.append( Upload_key_init.decrypt(arr[1]) ) #respective variables by decrypting them first
print(encrypted_pass_output_lst,encrypted_desc_output_lst) #printing the lists
return render_template('file-manip.html',message = "file uplaoded succesfully")
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
####################################
####################################
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
str_main.html (基本html文件)
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.0/css/bulma.min.css">
</head>
<body>
{%block content%}
{%endblock%}
</body>
</html>
input.html (用于用户输入)
{%extends 'str_main.html'%}
{% block content %}
<div id = "suggest-input">
<form action = "/data-extract" method = "GET">
<input type ="number" placeholder="no. of suggestions",name="sug">
<input type= "submit",value = "click here">
</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"><a href="{{url_for('data_input')}}"><h6>Home</h6></a></div>
<div id = "btn-output-3"><a href ="{{url_for('disp_manip_menu')}}"><h6>Save</h6></a></div>
</div>
<div id = "output-head">
<h1>Here are the suggestions</h1>
</div>
<div id = "output-div">
<form id = "output-data" method = "POST" enctype = "multipart/form-data">
<table>
<tr>
<th>Password</th>
<th>Description</th>
</tr>
{% for i in final_lst %}
<tr>
<td> <a href ="{{url_for('show',id = i.id)}}">{{ i.passwd }}</a></td>
<td>{{ i.desc }}</td>
</tr>
{% endfor %}
</table>
</form>
</div>
{% endblock %}
modify.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 = "text" value ="{{found_entry.desc}}" name = "description">
<input type ="submit" value = "save change" >
</form>
</div>
{% endblock %}
file-manip.html (用于文件操作)
{% extends 'str_main.html' %}
{% block content %}
<p>Saving file</p>
<form method= "POST" action = "/generate/file-manip" enctype = "multipart/form-data">
<label>For the password storing file</label>
<input type = "file" value = "browse" name = "fileName">
<label>For the file storing the key</label>
<input type = "file" value = "key file" name = "keyfile">
<input type ="submit" value= "saving file">
</form>
<p>Uploading file</p>
<form method= "POST" action = "/generate/file-manip-upload" enctype = "multipart/form-data">
<label>For the password storing file</label>
<input type = "file" value = "browse" name = "Uploadfile">
<input type = "file" value = "key file" name = "Uploadkeyfile">
<input type ="submit" value= "saving file">
</form>
<br/>
<p>{{message}}</p>
{% endblock %}
当我在终端中选择了用于打印密码的所需文件时,出现以下错误。
for arr in reader_param:
_csv.Error: iterator should return strings,not bytes (did you open the file in text mode?)
我试图在代码的必需部分中更改读写模式,但是没有任何效果。因此,我想知道是什么导致了此错误,以及如何解决该问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。