Python Web

Python Web#

! pip install web.py
Hide code cell output
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: web.py in d:\programdata\miniconda3\lib\site-packages (0.62)
Requirement already satisfied: cheroot in d:\programdata\miniconda3\lib\site-packages (from web.py) (8.5.2)
Requirement already satisfied: jaraco.functools in d:\programdata\miniconda3\lib\site-packages (from cheroot->web.py) (3.5.0)
Requirement already satisfied: six>=1.11.0 in d:\programdata\miniconda3\lib\site-packages (from cheroot->web.py) (1.16.0)
Requirement already satisfied: more-itertools>=2.6 in d:\programdata\miniconda3\lib\site-packages (from cheroot->web.py) (8.12.0)
Did not find path entry D:\ProgramData\Miniconda3\bin

上面的输出被隐藏了,点击 “+” 号可以展开。查看官方文档学习如何隐藏单元格输出

%%writefile 是 Jupyter Notebook 的一个魔法命令,表示将下面的内容写入到 app.py 文件中。

%%writefile ../_tmp/web_app.py
import web

urls = ( '/', 'index' )
app = web.application(urls, globals())

class index:
    def GET(self):
        greeting = "Hello World"
        return greeting

if __name__ == "__main__":
    app.run()
Writing ../_tmp/app.py

%run 也是 Jupyter Notebook 的魔法命令,它将会执行 app.py 文件(使用 8081 端口)。 但是,下面这一行代码一旦运行就不会停止,因此上传代码到 Readthedocs 后就会在编译时卡住,这里就给它先注释掉了。

# %run ../_tmp/web_app.py 8081
http://0.0.0.0:8081/
127.0.0.1:63598 - - [20/Dec/2023 21:12:15] "HTTP/1.1 GET /" - 200 OK
127.0.0.1:63598 - - [20/Dec/2023 21:12:16] "HTTP/1.1 GET /favicon.ico" - 404 Not Found

使用这段程序时,应当解开上面一行代码的注释,然后访问 http://localhost:8081/,就可以看到 Hello world 被成功打印了。