kickfick123 2018-01-27 05:59 采纳率: 100%
浏览 37771
已采纳

'str' object has no attribute 'get'咋解决?

本人学医,凭兴趣自学python,真心不易,现在遇到一个问题:在写一个简单的注册提交页面,是想通过class将数据存储到本地的txt文件,在输入username和password,submit到register/add时,但遇到了下面的问题:

图片说明

请各位大神帮助看是什么问题。

下面是源代码,看看还有没有其他什么问题。谢谢!

app.py

 from flask import (
    Flask,
    render_template,
    request,
    redirect,
)

from Models import (Users, Requirements)
import time
import os

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return render_template('/index.html')


@app.route('/login')
def login():
    return render_template('/login.html')


@app.route('/register')
def register():
    return render_template('/register.html')


@app.route('/register/add', methods=['POST'])
def register_add():

    if request.method == 'POST':
        form = request.form
        print('打印', form)
        u = Users.new(form)
        u.save()

    return redirect('/login')


@app.route('/post', methods=['GET'])
def post_message():
    return render_template('/post.html')


@app.route('/post/add', methods=['POST'])
def post_add():

    if request.method == 'POST':
        form = request.form
        u = Requirements(form)
                u = Requirements.new(form)
        u.save()

    return redirect('/post')


if __name__ == '__main__':
    config = dict(
        debug=True,
        host='0.0.0.0',
        port=2000,
    )
    app.run(**config)

Model.py

 from random import Random
import json
import os


def save(data, path):

    m = json.dumps(data, ensure_ascii=False)
    # path = os.path.dirname(__file__)
    with open(path, 'a+') as f:
        f.read()
        f.write(m + '\n')
        f.close()


def load(path):
    with open(path, 'r', encoding='utf-8') as f:
        s = f.read()
        m = json.dumps(s, ensure_ascii=False)
        print('加载', type(m), m)
        t = json.loads(m)
        print('加载', type(t), t)
        return t


def random_str(randomlength=16):
    s = ''
    chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
    length = len(chars) - 1
    random = Random()
    for i in range(randomlength):
        s += chars[random.randint(0, length)]
    return s


class Model(object):

    @classmethod
    def db_path(cls):
        root = os.path.dirname(__file__)
        classname = cls.__name__
        path = '{}/data/{}.txt'.format(root, classname)
        return path


    @classmethod
    def all(cls):
        """
        all 方法(类里面的函数叫方法)使用 load 函数得到所有的 models
        """
        path = cls.db_path()
        models = load(path)
        ms = [cls.new(m) for m in models]
        return ms

    @classmethod
    def new(cls, form):
        m = cls(form)
        return m


    def save(self):
        models = self.all()
        path = self.db_path()
        l = [m.__dict__ for m in models]
        save(l, path)


class Users(Model):
    def __init__(self, form):
        self.id = random_str()
        self.username = form.get('username', '')
        self.password = form.get('password', '')


class Requirements(Model):
    def __init__(self, form):
        self.id = form.get('id', None)
        self.province = form.get('province', '')
        self.city = form.get('city', '')
        self.post_content = form.get('post_content', '')
        self.contact_requirement_method = form.get('contact_requirement_method', '')

最后搞定了,采取了下面这种方式,然后有修改了Model部分内容

    if request.method == 'POST':
        formdata = request.form
        form = formdata.to_dict()
        u = Users.new(form)
        u.save()

  • 写回答

9条回答 默认 最新

  • 在路上挥霍 2018-01-27 08:59
    关注

    1.获取客户端提交的表达数据,数据类型为ImmutableMultiDict
    formData = request.form
    2.将提取的数据转化成字典
    formDict = formData.to_dict()
    3.提取客户端提交的json字符串
    dataJsonString = formDict.keys()[0]
    4.将json字符串序列化成字典
    dataDict = eval(dataJsonString)

    这么干!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?

悬赏问题

  • ¥15 写一个可直接调用的函数,将32位有符号数转成另一个无符号的数
  • ¥15 CMAKE+VS2019+QT5.15.2组合进行二次编译
  • ¥15 nginx 配置静态html访问 ,后台登录时页面始终被重定向到登录页,无法访问到后台的静态html页
  • ¥20 自动登录的j2ee程序编译
  • ¥15 fluent模拟静态气体扩散
  • ¥15 java根据模板,生成word文档,需要带目录
  • ¥15 广告联盟的兜底广告是什么意思
  • ¥15 如何证明高斯噪声的包络公式
  • ¥150 寻找王者荣耀开发作者,合作或者解答
  • ¥15 关于cpci总线的几个问题,别用人工智能回答