您现在的位置:首页 >> 前端 >> 内容

web.py环境搭建与helloworld实例讲解

时间:2018/5/11 13:36:52 点击:

  核心提示:安装本人使用的是python3.6,因此会存在一点问题。不要用去github上下载包然后 python setup.py的方法,还是没装上。还会出现卸载不了的问题。直接使用pip install we...

安装

本人使用的是python3.6,因此会存在一点问题。不要用去github上下载包然后 python setup.py的方法,还是没装上。还会出现卸载不了的问题。

直接使用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,即可看到网页。因为此处是正则匹配所有字符,所以之后跟任何东西都是可以的,比如https://127.0.0.1:8080/121341

Tags:WE EB BP PY 
作者:网络 来源:hehangjian