-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
158 lines (126 loc) · 3.75 KB
/
Copy pathexample.py
File metadata and controls
158 lines (126 loc) · 3.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# -*- coding: utf-8 -*-
"""
Libra 框架示例应用
"""
from libra import Libra, Request, Response, render_template, Response
app = Libra()
# 基础路由示例
@app.route('/')
def index():
return '<h1>欢迎使用 Libra 框架</h1><p><a href="/hello">Hello</a></p>'
@app.route('/hello')
def hello():
return 'Hello, World!'
# RESTful API 示例
users = [
{'id': 1, 'name': 'Alice', 'email': 'alice@example.com'},
{'id': 2, 'name': 'Bob', 'email': 'bob@example.com'},
{'id': 3, 'name': 'Charlie', 'email': 'charlie@example.com'},
]
@app.get('/api/users')
def get_users():
"""获取用户列表"""
return {'users': users, 'total': len(users)}
@app.get('/api/users/<id>')
def get_user(id):
"""获取单个用户"""
for user in users:
if str(user['id']) == id:
return user
return Response.jsonify({'error': 'User not found'}, status=404)
@app.post('/api/users')
def create_user(request: Request):
"""创建用户"""
data = request.json
if not data or 'name' not in data:
return Response.jsonify({'error': 'Name is required'}, status=400)
new_id = max(u['id'] for u in users) + 1 if users else 1
new_user = {
'id': new_id,
'name': data['name'],
'email': data.get('email', '')
}
users.append(new_user)
return Response.jsonify(new_user, status=201)
@app.delete('/api/users/<id>')
def delete_user(id):
"""删除用户"""
for i, user in enumerate(users):
if str(user['id']) == id:
users.pop(i)
return Response.jsonify({'message': 'Deleted'})
return Response.jsonify({'error': 'User not found'}, status=404)
# 请求对象示例
@app.route('/request-info')
def show_request_info(request: Request):
"""展示请求信息"""
info = {
'method': request.method,
'path': request.path,
'query_string': request.query_string,
'args': request.args,
'remote_addr': request.remote_addr,
'headers': dict(list(request.headers.items())[:5]), # 只显示前5个
}
return Response.jsonify(info)
# 模板渲染示例
@app.route('/template')
def template_demo():
"""模板渲染示例"""
title = 'Libra 框架'
items = ['功能1', '功能2', '功能3']
template_str = '''
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ title }}</h1>
<h2>功能列表:</h2>
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
</body>
</html>
'''
return render_template(template_str, title=title, items=items)
# 请求前后钩子示例
@app.before_request
def before():
"""请求前执行的函数"""
# 可以在这里做认证检查等
pass
@app.after_request
def after(response):
"""请求后执行的函数"""
response.set_header('X-Powered-By', 'Libra Framework')
return response
# 错误处理示例
@app.route('/error-demo')
def error_demo():
"""演示错误响应"""
from libra import BadRequestError, NotFoundError
import random
choice = random.choice(['bad_request', 'not_found', 'ok'])
if choice == 'bad_request':
raise BadRequestError('这是一个错误请求')
elif choice == 'not_found':
raise NotFoundError('资源未找到')
else:
return '正常响应'
if __name__ == '__main__':
print("=" * 50)
print("Libra 框架示例应用")
print("=" * 50)
print("访问以下地址测试:")
print(" - http://127.0.0.1:5000/")
print(" - http://127.0.0.1:5000/hello")
print(" - http://127.0.0.1:5000/api/users")
print(" - http://127.0.0.1:5000/request-info")
print(" - http://127.0.0.1:5000/template")
print(" - http://127.0.0.1:5000/error-demo")
print("=" * 50)
app.run(debug=True)