首页 > 解决方案 > Python Flask:如何保存页面中的数据

问题描述

有人用python很好地包装烧瓶吗?我有一个注册表单,但我不知道如何保存该页面的数据,例如姓名和密码,以便稍后阅读。

保存到一个单独的文件类型:

file = open(file.txt)
file.write(username + password)

当我已经托管页面时不起作用。

标签: pythonflask

解决方案


首先,你能提供你的代码吗?你想创造什么?它是一个需要注册和授权的简单 Web 应用程序,还是只是您想从中获取一些数据的表单?

其次,网上有一些关于Flask注册的不错的教程。此外,您可以阅读内容。这里有一本 Flask 学生用书。如果本教程不适合您,您可以搜索不同的内容。

第三,关于从烧瓶应用程序中将数据保存在文本文件 .txt 中。你可以检查这个答案

UPD。对于带有文件的最后一个变体。

应用程序.py

from flask import Flask, render_template, request 

app = Flask(__name__) 
     
@app.route('/') 
def index(): 
    return render_template('index.html') 
     
@app.route('/', methods = ['POST']) 
def get_data(): 
    login = request.form['login']
    password = request.form['password']
    if request.method == 'POST': 
        with open('data.txt', 'a+') as f:
            f.write(str(login) + ' ' + str(password) + '\n')
    return render_template("index.html") 
     
if __name__ == '__main__': 
    app.run(debug = True) 

模板/index.html

<html> 
   <body> 
    
     <form action="" method="POST"> 
         <p>Login <input name="login" /></p> 
         <p>Password <input name="password" /></p> 
         <p><input type="submit"></p> 
      </form> 
       
   </body> 
</html> 

推荐阅读