python web(bottle)学习笔记(7)——实战编码(POST提交代理商信息)

本节我们的主要任务是通过POST提交数据信息到数据库中;
*此章节中主要注意留意的一个问题点就是POST 表单中提交是中文的时候bottle如何接收

上一个章节我们已经把首页给渲染出来,至于案例选项也是一样同理一样的方式读取数据并展示,再这里我就不多讲了!

本节主要是讲一下当Form表单提交包含有中文的时候,该怎么处理?
如图示:


image.png

第1步:让HTML页面以POST方式提交数据

image.png

第2步:在pricing处接收post数据请求

# 合作提交申请,代理商申请--主要是写入数据库
@route('/pricing', method='POST')
@route('/signup', method='POST')
def do_signup():
    print(request.path)
    if request.path.find('signup') != -1:
        # Bottle通过 FormsDict.getunicode() 和属性访问实现了转码,但不支持字典形式的访问。通过字典形式的访问,将直接返回服务器返回的字符串,未经处
        name = request.forms.getunicode('name')
        tel = request.forms.getunicode('tel')
        qq = request.forms.getunicode('qq')
        email = request.forms.getunicode('email')
        city = request.forms.getunicode('city')
        host = request.forms.getunicode('host')
        desc = request.forms.getunicode('desc')
        msg = put_agent_data(name, tel, qq, email, city, host, desc)
    else:
        # Bottle通过 FormsDict.getunicode() 和属性访问实现了转码,但不支持字典形式的访问。通过字典形式的访问,将直接返回服务器返回的字符串,未经处
        name = request.forms.getunicode('name')
        tel = request.forms.getunicode('tel')
        city = request.forms.getunicode('city')
        host = request.forms.getunicode('host')
        desc = request.forms.getunicode('desc')
        msg = put_pricing_data(name, tel, city, host, desc)

    return msg

注意接收的时候需要使用: request.forms.getunicode('name'),如果使用的是 request.forms.ge('name')接收到的中文是乱码的!

第3步:提交到数据库中进行保存

def put_pricing_data(name, tel, city, host, desc):
    """
    提交带来商合作信息
    :return:
    """
    message = ''
    if not (name and tel and city and host):
        message = "表单不允许为 空!"
        return '-2'
    else:
        # sql = "insert into tp_agent(name,telephone,qq,email,city,company,introduct) VALUES('%s','%s','%s','%s','%s','%s','%s')" % (
        #     name, tel, qq, email, city, host, desc)
        # result = writeDb(sql, data)
        sql = """
                    INSERT INTO
                        tp_agent(name,telephone,city,company,introduct)
                    VALUES(%s,%s,%s,%s,%s)
                """
        print(sql)
        data = (name, tel, city, host, desc)
        print(data)
        result = writeDb(sql, data)
        if result:
            message = '0';
        else:
            message = '-1';

    return message

结束语:

再处理中文的时候,我这里遇到了问题,查了一下官方的文档才知道!╮(╯▽╰)╭

其他系列文章目录:

python web(bottle)学习笔记(1)——前言
python web(bottle)学习笔记(2)——python 开发环境准备
python web(bottle)学习笔记(3)——‘我爱python’程序动起来
python web(bottle)学习笔记(4)——实战开篇(初步需求准备)
python web(bottle)学习笔记(5)——实战开篇(数据库篇)
python web(bottle)学习笔记(6)——实战编码(首页模板渲染)
python web(bottle)学习笔记(7)——实战编码(POST提交代理商信息)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容