学习web.py——01(环境搭建与hello world)

安装

本人使用的是python3.6,因此会存在一点问题。不要用去github上下载包然后 python setup.py的方法,还是没装上。还会出现卸载不了的问题。关于卸载,可以参考这个解决方案 https://stackoverflow.com/questions/1550226/python-setup-py-uninstall ,可以卸载。

直接使用 pip install web.py==0.40.dev0 ,完美运行。


Hello World

首先写入url的mapping

urls = ("/.*", "hello")

可以是多组元素,比如:

url = (
    # '/(.*)','index'
    '/', 'Index',
    '/new', 'New'
)

其中,前面的正则,根据在地址栏中输入的后缀,正则匹配,传递给对应的类。

class hello:
    def GET(self):
        return 'Hello, world!'

定义类

class hello:
    def GET(self):
        return 'Hello, world!'

这里的类名和url中的是对应的。简单地说,就是当正则匹配到时,就使用应用的类中的方法。

这里也可以return一个网页

return open('Index.html','rb').read().decode('utf-8')

因为我这个网页是中文的,所以要转换一下。

完整代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/5/9 16:44
# @Author  : He Hangjiang
# @Site    : 
# @File    : 01.py
# @Software: PyCharm

import web

url = (
    '/(.*)','index'
)

app = web.application(url,globals())

class index:
    def GET(self,name):
        return open('Index.html','rb').read().decode('utf-8')

if __name__ == '__main__':
    app.run()

在pycharm中运行,在浏览器中输入127.0.0.1:8080,即可看到网页。因为此处是正则匹配所有字符,所以之后跟任何东西都是可以的,比如 http://127.0.0.1:8080/121341

扫描二维码关注公众号,回复: 935855 查看本文章

猜你喜欢

转载自blog.csdn.net/hehangjiang/article/details/80258620