webpy获得用户post或者get的数据,上传文件示例,webpypost,webpy中通过web.


webpy中通过web.input()来保存用户的输入,用户的输入有几种,一种是普通的单个值的输入,另外一种是类似checkbox或者list的多个值,还有一种是上传的文件。

下面逐个说明:

1、 获得单个值输入,例如文本框输入

import webclass TestInput:    def POST(self):        i = web.input()        name = i.get('name')        return '您的名字是',name

2、 webpy获得checkbox的值

首先需要在界面上有checkbox让用户输入,如下html

<form method="POST"><input type="checkbox" name="id" value="1" id="chk1"> <label for="chk1">chk1</label> <input type="checkbox" name="id" value="1" id="chk1"> <label for="chk1">chk1</label> <input type="checkbox" name="id" value="1" id="chk1"> <label for="chk1">chk1</label> <input type="checkbox" name="id" value="1" id="chk1"> <label for="chk1">chk1</label> <input type="submit"/></form>

这样我们也是处理POST请求,下面代码可以获得用户选择checkbox的值:

import webclass TestInput:    def POST(self):        #这里给web.input传了一个key为id,职位空数组的参数        i = web.input(id=[])        ids = i.get('id')        #其他处理

3、 webpy上传文件示例:

如下示例代码:

class UploadImage:    '''    上传文件处理    '''    def POST(self):        i = web.input(image={})        filename = i.image.filename        name,ext = os.path.splitext(filename)        ext = ext.lower()        safeImageExts =('.png','.jpeg','.jpg','.gif')        if not ext in safeImageExts:            return 'xxx' #提示用户文件类型错误        saveToDir = 'saveto path'        if not os.path.exists(saveToDir):            os.makedirs(saveToDir)        newName = '%s%s'%(urlName,ext)        saveToPath = os.path.join(saveToDir,newName)        #下面一行保存文件        img.save(saveToPath)        return '<script>parent.uploadCallback(%s);</script>'% (json.dumps({'success':True,'url':url}),) #可以根据需要修改此处

上面的例子都是用的POST请求,但是GET请求使用方法也完全一样(除了不能上传文件之外)。

评论关闭