0 webpy安装
# For Python 2.7
pip2 install web.py==0.40
# For Python 3
python3 -m pip install web.py==0.40
或者下载源码,手动安装
webpy源码下载地址:https://github.com/webpy/webpy/releases
unzip webpy-0.40.zip
cd webpy-0.40/
python3 setup.py install
helloworld测试
import web
import logging
urls=('/', 'Index')
logging.basicConfig(level=logging.NOTSET)
app = web.application(urls, globals())
class Index:
def GET(self):
logging.info('你好世界')
web.header('Content-Type', 'text/html;charset=UTF-8')
return '你好世界'
def notfound():
return web.notfound("Sorry, the page you were looking for was not found.")
if __name__ == '__main__':
app.notfound = notfound;
app.run()
运行
1 中文乱码怎么解决:
修改,\web\template.py, line 1016:
return Template(open(path).read(), filename=path, **self._keywords)
为
return Template(open(path,encoding='utf-8').read(), filename=path, **self._keywords)
注:如果是python2
则改为
return Template(open(path).read().decode('utf-8'), filename=path, **self._keywords)
2 数据库怎么改成sqlite?
modle.py中的
db = web.database(dbn="mysql", db='test.db')
改成
db = web.database(dbn="sqlite", db='test.db')
然后写一个创建表的接口:
def create_test_db():
import sqlite3
conn = sqlite3.connect('test.db')
conn.execute('''CREATE TABLE entries (
id integer primary key autoincrement,
name TEXT,
age TEXT,
posted_on DATETIME
);''')
conn.close()
if __name__ == '__main__':
create_test_db()
3 多选的Checkbox怎么取值?
form = web.form.Form(
web.form.Checkbox('apple', value='apple', description='苹果'),
web.form.Checkbox('pear',value='pear', description='梨'),
web.form.Checkbox('mango',value='mango', description='芒果', checked=True)
)
取值
is_apple_checked = 'apple' in web.input(apple=[]).apple
is_pear_checked = 'pear' in web.input(pear=[]).pear
is_mango_checked = 'mango' in web.input(mango=[]).mango
4 下拉框的使用
form = web.form.Form(
web.form.Dropdown('state', ['sleep','ready','ok'], description='状态')
)
取值
state=form.d.state
5 缓存的使用
存:
web.setcookie('username', 'myname')
取:
username=web.cookies().get('username')
在html中取缓存
$if 'admin' == cookie().get('username'):
6 不打开新的窗口执行GET方法
window.location.href='/xxxx';
如果要打开新窗口,则用
window.open("./xxxx");
7 html中如何判断单选radio的勾选
全部
路飞
索隆
娜美
8 怎么html模板中,怎么通过javascript执行post
// ajax 对象
function ajaxObject() {
var xmlHttp;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("您的浏览器不支持AJAX!");
return false;
}
}
}
return xmlHttp;
}
// ajax post请求:
function ajaxPost ( url , data , succ , fail , loading ) {
var ajax = ajaxObject();
ajax.open( "post" , url , true );
ajax.setRequestHeader( "Content-Type" , "application/x-www-form-urlencoded" );
ajax.onreadystatechange = function () {
if( ajax.readyState == 4 ) {
if( ajax.status == 200 ) {
if (succ){succ( ajax.responseText );}
}
else {
if (fail){
fail( "HTTP请求错误!错误码:"+ajax.status );
}
}
}
else {
if (loading){loading();}
}
}
ajax.send( data );
}
首先,把上面两个函数放到你的代码中,使用例子:
var url='/delete';
var data='12';
var r=confirm("确定删除本条吗?");
if (r==true)
{
ajaxPost(url, data, function(){
alert("成功");
},function(){
alert("失败");
});
}
接收的地方:
urls=('/', 'Index',
'/delete', 'Delete',
)
class Delete:
def POST(self):
# 通过web.data()获取post过来的数据
itemid = web.data().decode('utf-8')
model.del_post(int(itemid))
raise web.seeother('/')
9 js脚本放哪里,怎么载入
存放位置:js脚本放在static/js/ 目录中
载入方式:在对应的html文件中加入如下的代码即可
10 python3.7.2使用web.py报错:generator raised StopIteration
见这里 https://blog.csdn.net/linxinfa/article/details/90030882
11 怎么给form填充数据
notice_form = web.form.Form(
web.form.Textarea('notice_txt',
web.form.notnull,
rows=3,
cols=173,
autofocus='autofocus',
description='公告',
placeholder='必填'),
web.form.Button('ok',description='发布')
)
form = notice_form()
# 向form中填充数据
form.fill({'notice_txt':'我是公告内容'})
12 url带参数
urls=('/', 'Index',
'/view/([0-9]+)', 'View',
'/hello/(.+)', 'Hello',
)
class View:
def GET(self, id):
return render.view(id)
class Hello:
def GET(self, txt):
return render.hello(txt)
访问
window.location.href='/hello/'+'world';
13 POST中获取form的值
假设有个Textarea
web.form.Textarea('notice_txt',
web.form.notnull,
rows=3,
cols=173,
autofocus='autofocus',
description='公告',
placeholder='必填')
在POST中想要获取它的值,方法如下
notice_text = web.input(notice_text={})["notice_text"]
补充:
1 python中的静态变量实现:
class GenId(object):
__count = 0
@classmethod
def get_count(cls):
return cls.__count
@classmethod
def set_count(cls, num):
cls.__count = num
使用
genId=GenId().get_count()+1
GenId().set_count(genId)
2 设置表格的边框厚度为0
3 pre标签自动换行
pre{
white-space:pre-wrap;/*css-3*/
white-space:-moz-pre-wrap;/*Mozilla,since1999*/
white-space:-pre-wrap;/*Opera4-6*/
white-space:-o-pre-wrap;/*Opera7*/
word-wrap:break-word;/*InternetExplorer5.5+*/ }