【Web开发】Python实现Web服务器(Bottle框架)

时间:2022-10-04 08:59:35

Django - The Web framework for perfectionists with deadlines. Flask - The Python micro framework for building web applications. Tornado - Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed. fastapi - FastAPI framework, high performance, easy to learn, fast to code, ready for production web.py - web.py is a web framework for python that is as simple as it is powerful. CherryPy - CherryPy is a pythonic, object-oriented HTTP framework. https://cherrypy.dev Pyramid - Pyramid - A Python web framework justpy - An object oriented high-level Python Web Framework that requires no frontend programming weppy - The web framework for inventors

【Web开发】Python实现Web服务器(Bottle框架)

1、简介

官网地址: https://bottlepy.org/docs/dev/

Bottle 是一个快速、简单、轻量级的 Python WSGI 微型 Web 框架。它只有一个文件,只依赖 Python 标准库 。

<font color=blue>Bottle 是一个用于Python的快速、简单和轻量级的WSGI微型 web 框架。它作为单个文件模块分发,除了Python 标准库之外没有其他依赖项。</font>

  • URL映射(Routing): 将URL请求映射到Python函数,支持动态URL,且URL更简洁。
  • 模板(Templates): 快速且pythonic的 内置模板引擎 ,同时支持 mako , jinja2 和 cheetah 等模板。
  • 基础功能(Utilities): 方便地访问表单数据,上传文件,使用cookie,查看HTTP元数据。
  • 服务器: 内置HTTP开发服务器并支持 paste, bjoern, gae, cherrypy 或任何其他 WSGI 功能强大的HTTP服务器。

2、安装

2.1 安装virtualenv

 virtualenv用来创建独立的Python 虚拟环境,可以将每个项目与其他项目独立开来,互不影响,解决了依赖包版本冲突的问题。安装virtualenv virtualenv是一个Python包。

virtualenvwrapper 是对 virtualenv 的功能扩展,可以管理全部的虚拟环境,用单个命令方便切换不同的虚拟环境。

  • 安装virtualenv
pip install virtualenv
pip install virtualenvwrapper  # 这是对virtualenv的封装版本,一定要在virtualenv后安装 
#pip install virtualenvwrapper-win

【Web开发】Python实现Web服务器(Bottle框架)【Web开发】Python实现Web服务器(Bottle框架)

  • 创建虚拟环境
mkdir d:\test_bottle
cd d:\test_bottle & d: # 进入该文件
virtualenv myenv # 创建一个名字为envname的虚拟环境
virtualenv -p python2 myenv # 如果安装了多个python版本,如py2和py3,需要指定使用哪个创建虚拟环境
virtualenv --no-site-packages myenv #如果创建一个不带已经安装到系统的中第三方包的环境
dir  # 查看当前目录可以知道一个myenv 的文件已经被创建

【Web开发】Python实现Web服务器(Bottle框架)【Web开发】Python实现Web服务器(Bottle框架)

  • 激活虚拟环境
# 进入虚拟环境文件
cd myenv 
# 进入相关的启动文件夹
cd Scripts

# myenv\scripts\activate #如无法激活,直接进入到activate所在目录,使用.\activate激活
activate  # 启动虚拟环境
deactivate # 退出虚拟环境

【Web开发】Python实现Web服务器(Bottle框架)

  • 安装第三方库
python -m pip install xxx   # python3版本安装包
python2 -m pip install xxx  # python2版本安装包
  • 使用virtualenvwrapper创建虚拟环境
列出虚拟环境列表:workon 或者 lsvirtualenv 
新建虚拟环境:mkvirtualenv [虚拟环境名称] -p [路径] 
启动/切换虚拟环境:workon [虚拟环境名称] 
离开虚拟环境:deactivate 
删除虚拟环境:rmvirtualenv [虚拟环境名称] 
列举所有的环境:lsvirtualenv 
导航到当前激活的虚拟环境的目录中:cdvirtualenv 
显示 site-packages 目录中的内容:lssitepackages

2.2 VsCode配置的虚拟环境

把需要使用该环境的项目文件夹添加到工作区 按下ctrl+,打开设置;或者在文件菜单中打开设置 【Web开发】Python实现Web服务器(Bottle框架) 搜索框中搜索env,点击你的项目,在左边选扩展->python,如下图: 【Web开发】Python实现Web服务器(Bottle框架) 在Python:Venv Path一行添加你的虚拟环境文件夹,注意文件夹间以逗号分隔 之后搜索python path,左边选扩展->python,下拉找到Python:Python Path,填入你的虚拟环境中的python解析器路径,如图: 或者直接修改setting.json,在里面加上:"python.envFile": "${workspaceFolder}/.vscode/.env",如:

{
    "python.pythonPath": "/path/python.exe",
    "python.envFile": "${workspaceFolder}/.vscode/.env"
}

保存后重启VsCode编辑器即可。

The python.pythonPath setting is no longer used by the Python extension.
A new optional setting python.defaultInterpreterPath is introduced in the user and workspace scope, from which the extension will read the value when loading a project for the first time.
Changes to the python.defaultInterpreterPath will not be picked up by the Python extension once an interpreter is already selected for the workspace. The extension will also not set nor change the value of this setting, it will only read from it.
A VSCode internal storage is introduced which will now store the interpreter settings in the workspace & workspace folder scope. i.e workspace settings are no longer stored in settings.json/.code-workspace, but an internal storage.

You can change the value stored in workspace settings using Python: Select Interpreter command.
See the Python output channel to check the value of the interpreter selected.
You can clear the value stored using Python: Clear Workspace Interpreter Setting command.

工作区解释器的路径现在将存储在 VS Code 的持久存储中,而不是settings.json 文件中;
您可以使用Python: Select Interpreter 命令更改特定于工作区的值。在命令面板上使用该命令时,存在一个新选项来指定解释器路径。

2.3 安装bottle

安装最新的稳定版本 pip install bottle 或下载 bottle.py_ _(不稳定)进入项目目录。没有困难 1 python标准库以外的依赖项。Bottle 支持python 2.7和python 3 .

pip install bottle

【Web开发】Python实现Web服务器(Bottle框架)

wget http://bottlepy.org/bottle.py

【Web开发】Python实现Web服务器(Bottle框架)

3、测试

3.1 Hello World

  • 代码如下:
#!/usr/bin/env python3

from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    return template('<b>Hello {{name}}</b>!', name=name)

@route('/test')
def test():
    return "Hello World, 爱看书的小沐,2022!"
    
run(host='localhost', port=8080)
  • 测试结果如下: 【Web开发】Python实现Web服务器(Bottle框架)【Web开发】Python实现Web服务器(Bottle框架)【Web开发】Python实现Web服务器(Bottle框架)

3.2 JSON 响应

Web 应用通常以 JSON 格式发送响应。 Bottle 自动将 Python 词典转换为 JSON。

#!/usr/bin/env python3
from bottle import route, run

@route('/message')
def hello():
    return "爱看书的小沐!"  

@route('/cars')
def getcars():
    cars = [ {'name': 'Audi', 'price': 52642},
        {'name': 'Mercedes', 'price': 57127},
        {'name': 'Skoda', 'price': 9000},
        {'name': 'Volvo', 'price': 29000},
        {'name': 'Bentley', 'price': 350000},
        {'name': 'Citroen', 'price': 21000},
        {'name': 'Hummer', 'price': 41400},
        {'name': 'Volkswagen', 'price': 21600} ]
    return dict(data=cars)

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

3.3 获取Get请求

HTTP GET 方法请求指定资源的表示形式。

#!/usr/bin/env python3
from bottle import route, run, request, get

@route('/')
def hello():
    return "爱看书的小沐!"  

@get('/msg')
def message():
    name = request.query.name
    age = request.query.age

    return "{0} is {1} years old".format(name, age)

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

3.4 静态文件

使用static_file(),我们可以在 Bottle 中提供静态文件。

  • ./public/home.html:
<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home page</title>
</head>
<body>
    <p>This is 爱看书的小沐's page</p>
</body>
</html>
  • app.py:
#!/usr/bin/env python3
from bottle import route, run, static_file

@route('/')
def hello():
    return "爱看书的小沐!"  
    
@route('/<filepath:path>')
def server_static(filepath):
    return static_file(filepath, root='./public/')

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

3.5 过滤器

包含通配符的路由称为动态路由(与静态路由相对)。 它们可以同时匹配多个 URL。 通配符由括在尖括号中的名称组成(例如<名称>),并且可以接受一个或多个字符,直到下一个斜杠为止。

#!/usr/bin/env python3
from bottle import route, run

@route('/')
def hello():
    return "爱看书的小沐!"  

@route('/app/<myid:int>/')
def provide(myid):
    return "爱看书的小沐的学号是 {} ".format(myid)

@route('/app/<name:re:[a-z]+>/')
def provide(name):
    return "Name {} given".format(name)    

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

3.6 表单数据

  • public/index.html:
<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Home page</title>
</head>
<body>
    <form method="post" action="doform">
        <div>
            <label for="name">Name:</label>
            <input type="text"  name="name">
        </div>
        <div>
            <label for="age">Age:</label>
            <input type="text"  name="age">
        </div>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
  • app.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from bottle import route, run, post, request, static_file

@route('/hello')
def hello():
    return "爱看书的小沐!"

@route('/')
def server_static(filepath="index.html"):
    return static_file(filepath, root='./public/')

@post('/doform')
def process():

    name = request.forms.get('name')
    age = request.forms.get('age')
    return "Your name is {0} and you are {1}.".format(name, age)

run(host='localhost', reloader=True, port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)【Web开发】Python实现Web服务器(Bottle框架)

3.7 错误处理程序

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from bottle import route, run, error

@route('/')
def hello():
    return "爱看书的小沐!"

@route('/app/<myid:int>')
def provide(myid):
    return "Object with id {} returned".format(myid)

@error(404)
def error404(error):
    return '404 - the requested page could not be found'   

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

3.8 模板示例

模板引擎是一个旨在将模板与数据模型结合以生成结果文档的库。 默认情况下,Bottle 使用简单的模板引擎。

  • views/show_cars.tpl
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cars</title>
</head>
<body>
    <table border="5" bordercolor="#0000CC">
        <tr>
            <th>Name</th>
            <th>Price</th>
        </tr>
        % for car in cars:
        <tr>
            <td>{{car['name']}}</td>
            <td>{{car['price']}}</td>
        </tr>
        % end

    </table>
</body>
</html>
  • app.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from bottle import route, run, template, HTTPResponse

@route('/')
def hello():
    return "爱看书的小沐!"

@route('/cars')
def getcars():

    data = [ {'name': 'Audi', 'price': 52642},
        {'name': 'Mercedes', 'price': 57127},
        {'name': 'Skoda', 'price': 9000},
        {'name': 'Volvo', 'price': 29000},
        {'name': 'Bentley', 'price': 350000},
        {'name': 'Citroen', 'price': 21000},
        {'name': 'Hummer', 'price': 41400},
        {'name': 'Volkswagen', 'price': 21600} ]
    if data:
        return template('show_cars', cars=data)
    else: 
        return HTTPResponse(status=204)

run(host='localhost', port=8080, debug=True)

【Web开发】Python实现Web服务器(Bottle框架)

结语

如果您觉得该方法或代码有一点点用处,可以给作者点个赞,或打赏杯咖啡;╮( ̄▽ ̄)╭ 如果您感觉方法或代码不咋地//(ㄒoㄒ)//,就在评论处留言,作者继续改进;o_O??? 如果您需要相关功能的代码定制化开发,可以留言私信作者;(✿◡‿◡) 感谢各位大佬童鞋们的支持!( ´ ▽´ )ノ ( ´ ▽´)っ!!!