python使用get和post方法_Python的Bottle框架中实现最基本的get和post的方法的教程

# -*- coding: utf- -*-

#!/usr/bin/python

# filename: GETPOST_test.py

# codedtime: -- ::

import bottle

def check_login(username, password):

if username == '' and password == '':

return True

else:

return False

@bottle.route('/login')

def login():

if bottle.request.GET.get('do_submit','').strip(): #点击登录按钮

# 第一种方式(latin1编码)

## username = bottle.request.GET.get('username','').strip() # 用户名

## password = bottle.request.GET.get('password','').strip() # 密码

#第二种方式(获取username\password)(latin1编码)

getValue = bottle.request.query_string

## username = bottle.request.query['username'] # An utf8 string provisionally decoded as ISO-- by the server

## password = bottle.request.query['password'] # 注:ISO--(即aka latin1编码)

#第三种方式(获取UTF-8编码)

username = bottle.request.query.username # The same string correctly re-encoded as utf8 by bottle

password = bottle.request.query.password # The same string correctly re-encoded as utf8 by bottle

print('getValue= '+getValue,

'\r\nusername= '+username,

'\r\npassword= '+password) # test

if check_login(username, password):

return "

Your login information was correct.

"

else:

return "

Login failed.

"

else:

return '''

Username:

Password:

'''

bottle.run(host='localhost', port=)

这里注意说一下Bottle编码的问题,只有第三种方式会将我们输入的字符如果是UTF-8重新编码为UTF-8,当你的内容里有中文或其他非英文字符时,这种方式就显的尤为重要。

运行效果如下:

MjAxNTMzMDE3MjYzMQ==.jpg

2、POST方式:

# -*- coding: utf- -*-

#!/usr/bin/python

# filename: GETPOST_test.py

# codedtime: -- ::

import bottle

def check_login(username, password):

if username == '' and password == '':

return True

else:

return False

@bottle.route('/login')

def login():

return '''

Username:

Password:

'''

@bottle.route('/login', method='POST')

def do_login():

# 第一种方式

# username = request.forms.get('username')

# password = request.forms.get('password')

#第二种方式

postValue = bottle.request.POST.decode('utf-8')

username = bottle.request.POST.get('username')

password = bottle.request.POST.get('password')

if check_login(username, password):

return "

Your login information was correct.

"

else:

return "

Login failed.

"

bottle.run(host='localhost', port=)

登录网站、提交文章、评论等我们一般都会用POST方式而非GET方式,那么类似于第二种方式的编码就很用用处,能够正确的处理我们在Form中提交的内容。而第一种则可能会出现传说中的乱码问题,谨记!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值