代码实现点餐系统
时间: 2023-08-20 09:03:53 浏览: 151
点餐系统可以分为客户端和服务端两部分。客户端主要负责展示菜单、接收用户输入、显示订单等功能;服务端则负责处理客户端发送的请求,生成订单并将其保存到数据库中。
以下是一个简单的点餐系统的代码示例:
服务端代码:
```python
import sqlite3
# 连接数据库
conn = sqlite3.connect('orders.db')
c = conn.cursor()
# 创建订单表
c.execute('''CREATE TABLE IF NOT EXISTS orders
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
phone TEXT,
address TEXT,
items TEXT)''')
# 处理客户端请求
def handle_request(request):
if request['action'] == 'add_order':
# 添加新订单
name = request['name']
phone = request['phone']
address = request['address']
items = request['items']
c.execute('''INSERT INTO orders (name, phone, address, items)
VALUES (?, ?, ?, ?)''', (name, phone, address, items))
conn.commit()
return {'status': 'success'}
elif request['action'] == 'get_orders':
# 获取所有订单
c.execute('SELECT * FROM orders')
orders = c.fetchall()
return {'status': 'success', 'orders': orders}
else:
return {'status': 'error', 'message': 'Invalid action'}
# 关闭数据库连接
conn.close()
```
客户端代码:
```python
import requests
# 服务端地址
SERVER_URL = 'http://localhost:8000'
def show_menu(menu):
# 展示菜单
print('Menu:')
for item in menu:
print(f'{item["name"]}: {item["price"]}')
def get_order():
# 获取用户订单
items = []
while True:
item_name = input('Enter item name (or "done" to finish): ')
if item_name == 'done':
break
quantity = int(input('Enter quantity: '))
items.append({'name': item_name, 'quantity': quantity})
return items
def place_order():
# 下单
name = input('Enter your name: ')
phone = input('Enter your phone number: ')
address = input('Enter your address: ')
items = get_order()
response = requests.post(f'{SERVER_URL}/order', json={
'name': name,
'phone': phone,
'address': address,
'items': items
})
if response.status_code == 200:
print('Order placed successfully')
else:
print(f'Error placing order: {response.text}')
def view_orders():
# 查看所有订单
response = requests.get(f'{SERVER_URL}/orders')
if response.status_code == 200:
orders = response.json()['orders']
for order in orders:
print(f'{order[1]} ({order[2]}): {order[4]}')
else:
print(f'Error getting orders: {response.text}')
# 展示菜单
menu = [
{'name': 'Pizza', 'price': 10},
{'name': 'Burger', 'price': 5},
{'name': 'Fries', 'price': 3},
{'name': 'Coke', 'price': 2},
]
show_menu(menu)
# 处理用户输入
while True:
action = input('Enter action (order/view/quit): ')
if action == 'order':
place_order()
elif action == 'view':
view_orders()
elif action == 'quit':
break
else:
print('Invalid action')
```
注意,这只是一个非常简单的示例,实际的点餐系统可能需要更多的功能和更复杂的代码。
阅读全文