码迷,mamicode.com
首页 > 编程语言 > 详细

day-3.初识pythong框架bottle

时间:2017-08-05 12:34:49      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:html   world   stat   函数   错误   div   bsp   install   root   

   以下资料来自python语言及其应用第九章。

bottle与flask都不是内置模块,需要安装。(pip install 模块名)

    安装完后开始写练手网页的代码吧。

bottle1.py

技术分享
1 from bottle import route
2 from bottle import run
3 
4 @route(/)
5 def home():
6     return "Hello world!"
7 
8 run(host=localhost, port=9999) 
View Code

    bottle使用route装饰器关联url和函数,以上代码首页(/)在home函数做处理,输入 python bottle.py来运行服务器脚本。

    输入 http://lcoalhost:9999 你会看到Hello world。在此例中bottle使用了python内置的测试用的web服务器,此服务器多用于测试。

    如果想在首页加载html文件该如何操作?

    在当前目录写一个index.html文件。写好以下代码,bottle2.py

技术分享
from bottle import route
from bottle import run
from bottle import static_file

@route(/)
def main():
    return static_file(index.html, root= .)

run(host="localhost", port=9999)
View Code

  .代表的是当前文件夹,root指的是我们需要使用的文件所在的目录。

加载完文件,那如何关联url呢。bottle3.py

技术分享
from bottle import route
from bottle import run
from bottle import static_file


@route(/)
def home():
    return static_file(index.html, root=.)

@route(/echo/<thing>)
def echo(thing):
    return "say hello to my friend: %s!" % thing

run(host="localhost", port=9999)
View Code

    我们定义了一个新的函数echo(),并且指定了一个字符串参数。这就是例子中

@route(‘/echo/<thing>‘) 做的事情。路由中的 <thing> 表示 URL 中 /echo/ 之后的内容都
会被赋值给字符串参数 thing ,然后被传入 echo 函数。

  

bottle 还有许多其他的特性,例如你可以试着在调用 run() 时加上这些参数:
? debug=True ,如果出现 HTTP 错误,会创建一个调试页面;
? reloader=True ,如果你修改了任何 Python 代码,浏览器中的页面会重新载入。
详细的文档可以在开发者网站(http://bottlepy.org/docs/dev/)上找到。

 

day-3.初识pythong框架bottle

标签:html   world   stat   函数   错误   div   bsp   install   root   

原文地址:http://www.cnblogs.com/deanglc/p/7289802.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!