pull/1/head
root 1 year ago
commit 35bf9d63a1
  1. 40
      app.py
  2. 31
      readQueue.py
  3. 17
      templates/index.html

@ -0,0 +1,40 @@
from flask import Flask,render_template, request, Response
from faker import Faker
import json, pika
app = Flask(__name__)
def shop_random(n):
fake = Faker(locale='zh_CN')
# 随机生成姓名、商品、价格、地址,并返回一个字典
shop = {"response": "下单成功", "data": {fake.name(): [fake.word(), fake.pyint(), fake.address()] for i in range(n)}}
return shop
def send_queue(data={}):
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明一个名为 'message_queue' 的队列
channel.queue_declare(queue='message_queue')
# 将消息发送到队列中
channel.basic_publish(exchange='',
routing_key='message_queue',
body=data)
# 关闭连接
connection.close()
@app.route('/', methods=["GET", "POST"])
def index():
if request.method == 'POST':
num = int(request.form.get('shop', 100))
data = shop_random(num)
json_data = json.dumps(data, ensure_ascii=False) # 设置 ensure_ascii 为 False
send_queue(json_data)
return Response(json_data, content_type='application/json; charset=utf-8')
return render_template("index.html")
if __name__ == '__main__':
app.run(host="0.0.0.0",port=80)

@ -0,0 +1,31 @@
import pika
import pymysql
# 建立到 RabbitMQ 的连接
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明一个名为 'message_queue' 的队列
channel.queue_declare(queue='message_queue')
def callback(ch, method, properties, body):
# 这里处理从队列中获取到的消息
conn = pymysql.connect(host='localhost', user='root', password='123456')
cur = conn.cursor()
cur.execute('create database if not exists shop default charset "utf8";')
cur.execute('use shop;')
cur.execute('create table if not exists shop(name varchar(20), goods varchar(20), price int, address varchar(50));')
for k,v in eval(body.decode()).get('data').items():
cur.execute('insert into shop values(%s,%s,%s,%s);', (k, v[0], v[1], v[2]))
print(k, v[0], v[1], v[2])
conn.commit()
cur.close()
# 从 'message_queue' 队列中获取消息
channel.basic_consume(queue='message_queue',
on_message_callback=callback,
auto_ack=True)
print('Waiting for messages. To exit press CTRL+C')
channel.start_consuming()

@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>商城主页</title>
</head>
<body>
<center>
<h1>祝您购物愉快</h1>
<form action="/" method="post">
请输入采购的商品数量:<input type="number" name="shop">
<button type="submit">提交</button>
</form>
</center>
</body>
</html>
Loading…
Cancel
Save